NSDictionary setValue:forKey:

编程入门 行业动态 更新时间:2024-10-05 09:30:52
本文介绍了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]]; [文章发布]; }

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

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

这个类是不符合键值标题的键值编码

错误。这与Interface Builder无关,它只是代码。为什么我得到这个错误?

解决方案

首先,你使用 -setValue:forKey:您应该使用 -setObject:forKey:在字典上的。其次,你试图突破一个 NSDictionary ,这是一个不可变的对象,而不是一个 NSMutableDictionary 工作。如果您切换到使用 -setObject:forKey:,则可能会收到异常,告诉您该字典是不可变的。将文章初始化切换到

NSMutableDictionary * article = [[NSMutableDictionary alloc] init];

它应该工作。

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?

解决方案

First off, you're using -setValue:forKey: on a dictionary when you should be using -setObject:forKey:. Secondly, you're trying to mutate an NSDictionary, which is an immutable object, instead of an NSMutableDictionary, which would work. If you switch to using -setObject:forKey: you'll probably get an exception telling you that the dictionary is immutable. Switch your article initialization over to

NSMutableDictionary *article = [[NSMutableDictionary alloc] init];

and it should work.

更多推荐

NSDictionary setValue:forKey:

本文发布于:2023-11-26 19:04:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634814.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NSDictionary   setValue   forKey

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!