NSDictionary setValue:forKey: -- 获取“该类与键的键值编码不兼容”
我的程序中有一个简单的循环:
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];
}
它使用 ElementParser 库从 RSS 提要创建值字典(除了我省略的“标题”之外,还有其他值)。 self.articles 是一个 NSMutableArray,它存储 RSS 文档中的所有字典。
最后,这应该生成一个字典数组,每个字典都包含我需要的有关任何数组索引处的项目的信息。当我尝试使用 setValue:forKey:
时,它给出了
this class is not key valuecoding-dependent for the key "Title"
错误。这与 Interface Builder 无关,它只是代码。为什么我会收到此错误?
I have this simple loop in my program:
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];
}
It is using the ElementParser library to make a dictionary of values from an RSS feed (there are other values besides "title" which I have omitted). self.articles
is an NSMutableArray which is storing all of the dictionaries in the RSS document.
In the end, this should produce an array of dictionaries, with each dictionary containing the information I need about the item at any array index. When I try to use setValue:forKey:
it gives me the
this class is not key value coding-compliant for the key "Title"
error. This has nothing to do with Interface Builder, it is all code-only. Why am I getting this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,当您应该使用
-setObject:forKey:
时,您却在字典上使用了-setValue:forKey:
。其次,您尝试改变一个NSDictionary
,它是一个不可变的对象,而不是一个可以工作的NSMutableDictionary
。如果您切换到使用-setObject:forKey:
您可能会收到一个异常,告诉您字典是不可变的。将您的article
初始化切换到,它应该可以工作。
First off, you're using
-setValue:forKey:
on a dictionary when you should be using-setObject:forKey:
. Secondly, you're trying to mutate anNSDictionary
, which is an immutable object, instead of anNSMutableDictionary
, which would work. If you switch to using-setObject:forKey:
you'll probably get an exception telling you that the dictionary is immutable. Switch yourarticle
initialization over toand it should work.
这:
意味着字典是不可变的。如果您想更改其内容,请创建一个可变字典:
或者,您可以将字典创建为:
并在该方法末尾删除发布。
此外,在(可变)字典中添加/替换对象的规范方法是
-setObject:forKey:
。除非您熟悉键值编码< /a>,我建议您不要使用-valueForKey:
和-setValue:forKey:
。This:
means that the dictionary is immutable. If you want to change its contents, create a mutable dictionary instead:
Alternatively, you could create your dictionary as:
and drop the release at the end of that method.
Also, the canonical method to add/replace objects in a (mutable) dictionary is
-setObject:forKey:
. Unless you are familiar with Key-Value Coding, I suggest you don’t use-valueForKey:
and-setValue:forKey:
.