开发者

what's the difference between single key and keypath?

as shown in this page

[self setValue:[NSNumber numberWithInt:intValue] forKey:@"myObject.value"];

The answer was that "of course, it's a开发者_开发百科 key path not a single key", What does that mean?


A key is a string that identifies a property of an object. A key path is a list of keys separated by dots, used to identify a nested property.

Here's an example. If an object person has a property address, which itself has a property town you could get the town value in two steps using keys:

id address = [person valueForKey:@"address"];
id town = [address valueForKey:@"town"];

or in one step using a keyPath:

id town = [person valueForKeyPath:@"address.town"];

Have a look at Apple's docs on Key-Value Coding for further details.


valueForKey vs valueForKeyPath

[Objective-C KVC]
[Swift KVC]

  • valueForKey is about KVC
  • valueForKeyPath is KVC + dot syntax

You are able to use valueForKeyPath for root properties, but you are not able to use valueForKey for nested properties

A has -> B has -> C
//root properties
B *b1 = [a valueForKey:@"b"];

B *b2 = [a valueForKeyPath:@"b"];

//nested properties
C *c1 = [a valueForKey:@"b.c"]; //[<A 0x6000016c0050> valueForUndefinedKey:]: this class is not key value coding-compliant for the key b.c. (NSUnknownKeyException)
   
C *c2 = [a valueForKeyPath:@"b.c"];

Additional context

//access to not existing
[a valueForKey:@"d"]; //runtime error: [<A 0x600003404600> valueForUndefinedKey:]: this class is not key value coding-compliant for the key d. (NSUnknownKeyException)

//they both return `id` that is why it is simple to work with them
id id1 = [a valueForKey:@"b"];
B *b1 = (B*) id1;//[b1 isKindOfClass:[B class]]
//or
B *b2 = [a valueForKey:@"b"];

//Wrong cast
C *c1 = [a valueForKey:@"b"];
[c1 fooC]; //-[B fooC]: unrecognized selector sent to instance 0x600001f48980 (NSInvalidArgumentException)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜