2013-07-13 36 views
0

尋找幫助診斷以下錯誤:NSMutableArray的鍵值編碼錯誤

*終止應用程序由於未捕獲的異常 'NSUnknownKeyException',原因:「[< __NSCFBoolean 0x39d40da8>的setValue:forUndefinedKey:]:此類不是關鍵板球編碼的關鍵價值。「

下面的代碼:

NSMutableArray *soundNames = [[NSMutableArray alloc] initWithObjects:@"Random", @"Cricket", @"Mosquito", @"Fly", @"Owl", @"Scratching", @"Whistle", nil]; 

NSNumber *noObj = [NSNumber numberWithBool:NO]; 
NSMutableArray *soundValues = [[NSMutableArray alloc] initWithObjects:noObj, noObj, noObj, noObj, noObj, noObj, noObj, nil]; 

NSMutableDictionary *soundDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:soundNames, @"Sound Names", soundValues, @"Sound Values", nil]]; 

- (void)setSoundDictValue:(BOOL)value forKey:(NSString *)key 
{ 
    [[soundDict objectForKey:@"Sound Values"] setValue:[NSNumber numberWithBool:value] forKey:key]; 
    … 
} 

感謝 託尼。

回答

0

您正在錯誤地構建字典。爲什麼不只是做:

NSMutableDictionary *soundDict = [@{ 
    @"Random" : @NO, 
    @"Cricket" : @NO, 
    @"Mosquito" : @NO, 
    @"Fly" : @NO, 
    @"Owl" : @NO, 
    @"Scratching" : @NO, 
    @"Whistle" : @NO 
} mutableCopy]; 

那麼你setSoundDictValue:forKey:方法變爲:

- (void)setSoundDictValue:(BOOL)value forKey:(NSString *)key { 
    sound[key] = @(value); 
} 

與您的代碼的問題是比較容易看到,如果你把它分解了:

- (void)setSoundDictValue:(BOOL)value forKey:(NSString *)key { 
    NSArray *sounds = [soundDict objectForKey:@"Sound Values"]; 
    [sounds setValue:[NSNumber numberWithBool:value] forKey:key]; 
} 

,你可以請參閱,您嘗試在NSArray上致電setValue:forKey:

+0

迴應太快:)。推測你的意思是「soundDict [key] = @(value);」 ?如果是這樣,我得到編譯器錯誤:期望的方法來編寫字典元素找不到對象類型NSDictionary * – Tony

+0

如果我然後將聲明更改爲「NSMutableDictionary * soundDict」,我得到的聲明編譯器錯誤:不兼容的指針類型初始化NSMutableDictionary *與一個NSDictionary類型的表達式* – Tony

+0

查看我的更新,顯示如何創建一個可變字典。 – rmaddy