为什么在访问对象属性时使用KVC而不是简单的点语法? [英] Why should I use KVC rather than the simple dot syntax when accessing object properties?

查看:169
本文介绍了为什么在访问对象属性时使用KVC而不是简单的点语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个接收器类符合NSKeyValueProtocol,那么可以选择很长的时间:

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

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

或简称:

myInstance.integerProperty = 2;

这个KVC方法的意义是什么?什么时候有用?

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

推荐答案

首先,这些不一样,第二个应该是:

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

myInstance.integerProperty = [NSNumber numbwerWithInt:2];

如果 integerProperty NSNumber

一般来说,当你做最多的事情时,你使用第二种形式。当你想动态选择存储内容的属性时,你使用 setValue:forKey: valueForKey: ,考虑如何 valueForKeyPath: NSArray 工作(如果调用 valueForKey:对一个 NSArray 它将返回一个数组,其中每个对象是在 NSArray

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;
}

在上述情况下,使用 valueForKey:来实现我们的函数,即使我们不知道键是什么,因为它是作为参数传递的。

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.

这篇关于为什么在访问对象属性时使用KVC而不是简单的点语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆