Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary not key value coding-compliant for the key Test

I'm trying to use NSDictionary in a way that I can store NSArrays in it, but I can't even get it working for strings.

_times = [[NSDictionary alloc] init];
NSString *test = @"Test";
[_times setValue:@"testing" forKey:test];
NSLog(@"%@",[_times objectForKey:test]);

For the code above, I get the error message
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0x8b86540> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Test.'

Why would an NSString * not work as a key? In fact, that's precisely what the method calls for.

like image 208
Inbl Avatar asked Feb 24 '14 17:02

Inbl


People also ask

What is key-value coding?

Key-value coding is a mechanism enabled by the NSKeyValueCoding informal protocol that objects adopt to provide indirect access to their properties. When an object is key-value coding compliant, its properties are addressable via string parameters through a concise, uniform messaging interface.

What is NSDictionary in Objective c?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


2 Answers

NSDictionary is immutable, so you can't set value to it.
use NSMutableDictionary

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

I am including @Martin's comment here

In addition: Use setObject:forKey to set dictionary values. setValue:forKey is only needed for "Key-Value Coding" magic. setObject:forKey would also give a better error message if applied to an immutable dictionary.

like image 154
santhu Avatar answered Oct 20 '22 01:10

santhu


Also, for dictionaries, KVC is an inefficient way to set key/value pairs. Better to use the NSMutableDictionary method setObject:forKey:

like image 41
Duncan C Avatar answered Oct 20 '22 01:10

Duncan C