我正在尝试使用 NSDictionary
以一种我可以存储的方式 NSArrays
在里面,但我什至不能让它为字符串工作。
_times = [[NSDictionary alloc] init];
NSString *test = @"Test";
[_times setValue:@"testing" forKey:test];
NSLog(@"%@",[_times objectForKey:test]);
对于上面的代码,我收到错误消息
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 *
不能作为 key ?事实上,这正是该方法所需要的。
最佳答案
NSDictionary
是不可变的,因此您无法为其设置值。
使用 NSMutableDictionary
NSMutableDictionary *times = [[NSMutableDictionary alloc] init];
我在这里包括@Martin 的评论
此外:使用setObject:forKey
设置字典值。 setValue:forKey
仅在"Key-Value Coding"magic 时需要。 setObject:forKey
如果应用于不可变字典,也会给出更好的错误消息。
关于ios - NSDictionary 不符合键测试的键值编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21994546/