Question

I am having trouble with RestKit when I had a JSON response with @ symbols in the keys. After some debugging it seems the issue is happening in __NSCFDictionary

So I tried the following simple code:

NSArray *keys = [NSArray arrayWithObjects:@"@key1", @"@key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
                                                   forKeys:keys];
for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary valueForKey:key]);
}

And I am getting the following error:

[<__NSDictionaryI 0x618000268ac0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key key1.

Can someone please explain why I am getting this error and if there is any workaround?

Was it helpful?

Solution

You can't use @ in the keys in conjunction with valueForKey:. NSDictionary has some documented but perhaps unexpected behavior in that case: it strips the @ and invokes [super valueForKey:] with the new key. That looks for the key on the object, not in the dictionary's contents. No such key exists on instances of NSDictionary, so an exception is raised.

You should in general use objectForKey: to retrieve values from an NSDictionary.

Credit must go to Ken Thomases for his comments below, correcting earlier versions of this answer.

OTHER TIPS

Because you copied the code of someone who uses valueForKey: instead of objectForKey: without understanding what each is good for.

objectForKey: is what you should use. It takes the key that you pass in, and looks up the value for that key.

valueForKey: is a highly complicated method that looks at the text in the key, and does all kind of complicated things, for example a key of @"@sum" will add up some values. If that is what you want, fine. If you want to look up a value, use objectForKey. It does what you think it should do, and is usually several times faster than valueForKey: anyway.

As a rule of thumb: If I asked you whether you should use objectForKey: or valueForKey:, and you don't know what the difference is, use objectForKey:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top