Why should I use KVC rather than the simple dot syntax when accessing object properties?

◇◆丶佛笑我妖孽 提交于 2020-01-24 10:14:50

问题


There's the option to go the long way, if an receiver class conforms to the NSKeyValueProtocol:

[myInstance setValue:[NSNumber numberWithInt:2] forKey:@"integerProperty"];

or the short way:

myInstance.integerProperty = 2;

what's the point of this KVC method? When is this useful?


回答1:


First, those aren't the same, the second should be:

myInstance.integerProperty = [NSNumber numbwerWithInt:2];

if integerProperty is an NSNumber.

In general you use the second form when you are doing the most things. You use setValue:forKey: and valueForKey: when you want to dynamically choose the property to store things in. For instance, think about how valueForKeyPath: against an NSArray works (for reference, if you call -valueForKey: against an NSArray it will return an array where each object is the result of asking the corresponding object in that NSArray for that value:

- (NSArray *) valueForKey:(id)key {
  NSMutableArray *retval = [NSMutableArray array];

  for (NSObject *object in self) {
    [retval addObject:[object valueForKey:key]];
  }

  return retval;
}

In the above case we were able to use valueForKey: to implement our function even though we do not know what the key is beforehand, since it is passed in as an argument.



来源:https://stackoverflow.com/questions/1164014/why-should-i-use-kvc-rather-than-the-simple-dot-syntax-when-accessing-object-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!