NSDictionary setValue:forKey: — getting “this clas

2019-03-17 12:07发布

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?

2条回答
趁早两清
2楼-- · 2019-03-17 12:19

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.

查看更多
闹够了就滚
3楼-- · 2019-03-17 12:23

This:

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

means that the dictionary is immutable. If you want to change its contents, create a mutable dictionary instead:

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

Alternatively, you could create your dictionary as:

NSDictionary *article = [NSDictionary dictionaryWithObject:[[e selectElement: @"title"] contentsText] forKey:@"Title"];

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:.

查看更多
登录 后发表回答