【问题标题】:NSMutableArray key value coding errorNSMutableArray 键值编码错误
【发布时间】:2013-07-12 00:49:03
【问题描述】:

寻求帮助诊断以下错误:

* 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[<__nscfboolean> 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];
    …
}

谢谢 托尼。

【问题讨论】:

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


    【解决方案1】:

    您正在错误地构建字典。为什么不这样做:

    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:

    【讨论】:

    • 回复太快了:)。大概你的意思是“soundDict[key] = @(value);” ?如果是这样,我得到编译器错误:Expected method to write dictionary element not found on object of type NSDictionary *
    • 如果我随后将声明更改为“NSMutableDictionary *soundDict”,则在声明中出现编译器错误:Incompatible pointer types initializing NSMutableDictionary * with an expression of type of NSDictionary *
    【解决方案2】:

    当您在数组上调用 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 的属性。你到底想做什么?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 2012-08-18
      • 2013-03-30
      • 1970-01-01
      • 2017-10-24
      相关资源
      最近更新 更多