NSDictionary setValue:forKey: - 获取"此类不是密钥值编码兼容的密钥"

Log*_*man 24 objective-c nsdictionary data-structures

我的程序中有这个简单的循环:

for (Element *e in items)
{
    NSDictionary *article = [[NSDictionary alloc] init];
    NSLog([[e selectElement: @"title"] contentsText]);
    [article setValue: [[e selectElement: @"title"] contentsText] forKey: @"Title"];

    [self.articles insertObject: article atIndex: [self.articles count]];
    [article release];
}
Run Code Online (Sandbox Code Playgroud)

它使用ElementParser库从RSS提要中创建值的字典(除了"title"之外还有其他值,我省略了).self.articles是一个NSMutableArray,它存储RSS文档中的所有字典.

最后,这应该产生一个字典数组,每个字典包含我需要的关于任何数组索引的项的信息.当我尝试使用setValue:forKey:它时,给我了

this class is not key value coding-compliant for the key "Title"

错误.这与Interface Builder无关,它只是代码.为什么我收到此错误?

Lil*_*ard 90

首先,-setValue:forKey:当你应该使用时,你正在使用字典-setObject:forKey:.其次,你试图改变一个NSDictionary不可变的对象,而不是一个NSMutableDictionary可以工作的对象.如果你切换到使用-setObject:forKey:你可能会得到一个异常,告诉你字典是不可变的.将article初始化切换到

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

它应该工作.


小智 9

这个:

NSDictionary *article = [[NSDictionary alloc] init];
Run Code Online (Sandbox Code Playgroud)

意味着字典是不可变的.如果要更改其内容,请改为创建可变字典:

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

或者,您可以将字典创建为:

NSDictionary *article = [NSDictionary dictionaryWithObject:[[e selectElement: @"title"] contentsText] forKey:@"Title"];
Run Code Online (Sandbox Code Playgroud)

并在该方法结束时删除该版本.

此外,在(可变)字典中添加/替换对象的规范方法是-setObject:forKey:.除非您熟悉键值编码,否则我建议您不要使用-valueForKey:-setValue:forKey:.