NSDictionary is not a key value compatible with the encoding for a key test

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

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

In the above code, 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 does NSString * not work as a key? In fact, this is what the method requires.

+7
ios objective-c nsstring nsdictionary
source share
2 answers

NSDictionary is immutable, so you cannot set its value.
use NSMutableDictionary

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

I include a comment by @Martin here

Additionally: use setObject:forKey to set the dictionary values. setValue:forKey is only required for magic key encoding . setObject:forKey will also give a better error message if applied to an immutable dictionary.

+21
source share

In addition, for dictionaries, KVC is an inefficient way to set key / value pairs. It is better to use the NSMutableDictionary setObject: forKey method:

+1
source share

All Articles