NSDictionary不是关键测试的关键值编码兼容

Inb*_*nbl 7 objective-c nsdictionary nsstring ios

我试图以NSDictionary一种我可以存储NSArrays在其中的方式使用,但我甚至无法让它为字符串工作.

_times = [[NSDictionary alloc] init];
NSString *test = @"Test";
[_times setValue:@"testing" forKey:test];
NSLog(@"%@",[_times objectForKey:test]);
Run Code Online (Sandbox Code Playgroud)

对于上面的代码,我收到错误消息
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0x8b86540> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Test.'

为什么NSString *不能作为关键?事实上,这正是该方法所要求的.

san*_*thu 22

NSDictionary是不可变的,所以你不能设置它的值.
使用NSMutableDictionary

NSMutableDictionary *times = [[NSMutableDictionary alloc] init];
Run Code Online (Sandbox Code Playgroud)

我在这里包括@ Martin的评论

另外:setObject:forKey用于设置字典值.setValue:forKey只需要"键值编码"魔术.如果应用于不可变字典,setObject:forKey也会给出更好的效果error message.

  • @Inbl:另外:使用`setObject:forKey`来设置字典值.`setValue:forKey`仅用于"键值编码魔术".如果应用于不可变字典,`setObject:forKey`也会给出更好的错误消息. (2认同)