单键和keypath之间有什么区别?

时间:2010-11-24 17:18:08

标签: objective-c

this

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

答案是“当然,这是一条关键路径而不是一把钥匙”,这是什么意思?

2 个答案:

答案 0 :(得分:13)

键是标识对象属性的字符串。键路径是由点分隔的键列表,用于标识嵌套属性。

这是一个例子。如果对象person具有属性address,其本身具有属性town,则可以使用键分两步获取城镇值:

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

或使用keyPath一步完成:

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

有关详细信息,请查看Apple Key-Value Coding上的文档。

答案 1 :(得分:0)

valueForKey 与 valueForKeyPath

[Objective-C KVC]

  • valueForKey 大约是 KVC
  • valueForKeyPathKVC + 点语法

您可以将 valueForKeyPath 用于根属性,但不能将 valueForKey 用于嵌套属性

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"];

附加上下文

//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)