NSMutableArray键值编码错误

时间:2013-07-13 17:23:02

标签: ios nsmutablearray key-value-coding uncaught-exception

寻求诊断以下错误的帮助:

*由于未捕获的异常'NSUnknownKeyException'而终止应用,原因:'[< __ NSCFBoolean 0x39d40da8> setValue:forUndefinedKey:]:此类不是密钥Cricket的密钥值编码。

以下是代码:

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];
    …
}

由于 贝。

2 个答案:

答案 0 :(得分: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];
}

如您所见,您尝试在setValue:forKey:上致电NSArray

答案 1 :(得分:0)

在数组上调用setValue:forKey时,它会对该数组中的每个对象调用setValue:forKey(请参阅https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html)。 [soundDict objectForKey:@"Sound Values"]soundValues相同,后者是NSNumbers的数组。 NSNumber没有名为Crickit的属性。你究竟想做什么?