目标 C - 动态属性的respondsToSelector [英] Objective C - respondsToSelector for dynamic properties

查看:65
本文介绍了目标 C - 动态属性的respondsToSelector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前面临的问题是检查对象 (NSManagedObject) 的属性是否存在.

I am currently facing the problem to check whether a property of an Object (NSManagedObject) exists or not.

不幸的是方法

[[MyObject class] respondsToSelector:@selector(myProperty)];

总是返回 NO.

我觉得是因为CoreData生成的属性是新样式属性ala

I think it's because the property generated by CoreData is a new style property ala

@property (nonatomic, strong) NSString *myProperty

那么有什么想法可以解决这个问题吗?

So any ideas how to solve this issue?

我非常感谢您的所有建议;)

I would really appreciate all of your suggestions ;)

提前致谢!亚历克斯

推荐答案

[[MyObject class] RespondsToSelector:...] 询问元对象是否响应该选择器.因此,实际上,它会询问是否存在带有该选择器的类方法.如果您有:

[[MyObject class] respondsToSelector:...] asks whether the metaobject responds to that selector. So, in effect, it asks whether there is a class method with that selector. Your code would return YES if you had:

+ (NSString *)myProperty;

它返回 NO,因为你有实例方法的等价物:

It returns NO because you have the equivalent of the instance method:

- (NSString *)myProperty;

您需要在类的实例上调用 respondsToSelector:.

You need to call respondsToSelector: on an instance of your class.

你通常可以直接在元类上使用 instancesRespondToSelector:(所以,[MyObject instancesRespondToSelector:...])但是只有当你创建一个对象,所以这是一个非启动器.但是,您可以通过普通的 NSEntityDescription 路由创建一个实例,并在其上测试 respondsToSelector:.

You could normally use instancesRespondToSelector: directly on the metaclass (so, [MyObject instancesRespondToSelector:...]) but Core Data synthesises the relevant method implementations only when you create an object, so that's a non-starter. You could however create an instance via the normal NSEntityDescription route and test respondsToSelector: on that.

因为都是核心数据,另一种方法是通过 entitiesByName 字典向 NSManagedObjectModel 询问相关的 NSEntityDescription 并检查实体描述的 propertiesByName 字典.

Since it's all Core Data, an alternative would be to ask the NSManagedObjectModel for the relevant NSEntityDescription via its entitiesByName dictionary and inspect the entity description's propertiesByName dictionary.

这篇关于目标 C - 动态属性的respondsToSelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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