0

寻求帮助诊断以下错误:

* 由于未捕获的异常“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];
    …
}

谢谢托尼。

4

2 回答 2

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,它是一个 NSNumber 数组。NSNumber 没有名为 Crickit 的属性。你到底想做什么?

于 2013-07-13T17:39:23.827 回答
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.

于 2013-07-13T17:37:04.800 回答