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.
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.
An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.
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.
Also, for dictionaries, KVC is an inefficient way to set key/value pairs. Better to use the NSMutableDictionary method setObject:forKey:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With