Objective-C: What is the difference between forKey and forKeyPath?

What is the difference between forKey and forKeyPath in the NSMutableDicitionary setValue method? I looked in the documents and they seemed to me the same. I tried the following code, but I could not 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); } 
+6
source share
3 answers

Both methods are part of Key-Value Coding and should not normally be used to access an item in dictionaries. They work only with keys of type NSString and require a specific syntax.

The difference between the two is that specifying one (one) key will simply look for this element.

An indication of a key path, on the other hand, follows a path through objects. If you have a dictionary of dictionaries, you can find the element at the second level using the key path, for example "key1.key2" .

If you just want to access items in a dictionary, you should use objectForKey: and setObject:forKey:

Edit to answer why valueForKey: should not be used:

  • valueForKey: only works for string keys. Dictionaries can use other objects for keys.
  • valueForKey: Handles keys that begin with the @ symbol differently. You cannot access items whose keys begin with @ .
  • Most importantly: using valueForKey: you say: "I am using KVC." There must be a reason for this. When using objectForKey: you simply access the elements in the dictionary through a natural, targeted API.
+7
source

Apple Documentation: NSKeyValueCoding Protocol Link

SetValue: forKey:

Sets the property of the recipient specified by this key to the specified value.

Example:

 [foo setValue:@"blah blah" forKey:@"stringOnFoo"]; 

SetValue: forKeyPath:

Sets the value for the property identified by the given key path for the given value.

Example:

 [foo setValue:@"The quick brown fox" forKeyPath:@"bar.stringOnBar"]; 
+3
source

keyPath can be used to navigate arbitrary object paths if they implement NSKeyValueCoding . They should not be NSDictionary s. For instance:

 NSString *departmentName = [self valueForKeyPath:@"[person.department.name"]; 

Although this is a slightly contrived example.

+1
source

Source: https://habr.com/ru/post/920226/


All Articles