What is the difference between forKey and forKeyPath in NSMutableDicitionary’s setValue method? I looked both up in the documentation and they seemed the same to me. I tried following code, but I couldn’t distinguish the difference.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:@"abc" forKey:@"ABC"];
[dict setValue:@"123" forKeyPath:@"xyz"];
for (NSString* key in dict) {
id val = [dict objectForKey:key];
NSLog(@"%@, %@", key, val);
}
Both methods are part of Key-Value Coding and should not generally be used for element access in dictionaries. They only work on keys of type
NSStringand require specific syntax.The difference between both of them is that specifying a (single) key would just look up that item.
Specifying a key path on the other hand follows the path through the objects. If you had a dictionary of dictionaries you could look up an element in the second level by using a key path like
"key1.key2".If you just want to access elements in a dictionary you should use
objectForKey:andsetObject:forKey:.Edit to answer why
valueForKey:should not be used:valueForKey:works only for string keys. Dictionaries can use other objects for keys.valueForKey:Handles keys that start with an “@” character differently. You cannot access elements whose keys start with@.valueForKey:you are saying: “I’m using KVC”. There should be a reason for doing this. When usingobjectForKey:you are just accessing elements in a dictionary through the natural, intended API.