如何使用键值编码判断对象是否存在密钥? [英] How do you tell if a key exists for an object using Key-Value Coding?

查看:108
本文介绍了如何使用键值编码判断对象是否存在密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个对象在iPhone SDK中是否有可写的@property。

I'd like to test whether an object has a writeable @property in the iPhone SDK.

这样做的一种可行方法是检查-valueForKey:方法,但这看起来相当不优雅!

One possible way of doing this is to check the -valueForKey: method, but that seems rather inelegant!

示例:

  @try {
    id *value = [instance valueForKey:@"myProperty"];
  }
  @catch (NSException * e) {
    // Key did not exist
  }

有更好的方法吗?

推荐答案

如果您正在创建正在检查的对象,您可以覆盖 valueForUndefinedKey: setValue:forUndefinedKey 做一些比提出异常更有用的事情。

If you are creating the object that is being checked, you could override valueForUndefinedKey: and setValue:forUndefinedKey to do something more useful than raising an exception.

另一方面,如果您试图在运行时内省您不了解的对象,则必须使用运行时方法来执行此操作。您可以使用objective-c运行时本身并调用 class_copyPropertyList protocol_copyPropertyList 并处理这些,或使用Foundation并在给定属性的KVC getter / setter的对象上调用 respondsToSelector ,例如,对于属性 foo 你会调用类似 [someObject respondsToSelector:NSSelectorFromString(@foo)];

If, on the other hand, you are trying to introspect objects you don't know about at runtime, you will have to use the runtime methods to do that. You can either use the objective-c runtime itself and call either class_copyPropertyList or protocol_copyPropertyList and deal with those, or use Foundation and call respondsToSelector on the object for the KVC getter/setters for a given property, e.g., for a property foo you would call something like [someObject respondsToSelector:NSSelectorFromString(@"foo")];.

这篇关于如何使用键值编码判断对象是否存在密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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