Objective C - 动态属性的respondsToSelector
我目前面临的问题是检查对象(NSManagedObject)的属性是否存在。
不幸的是该方法
[[MyObject class] respondsToSelector:@selector(myProperty)];
总是返回NO。
我认为这是因为 CoreData 生成的属性是一种新样式属性 ala
@property (nonatomic, strong) NSString *myProperty
所以有什么想法如何解决这个问题吗?
我非常感谢您的所有建议;)
提前致谢! 亚历克斯
I am currently facing the problem to check whether a property of an Object (NSManagedObject) exists or not.
Unfortunately the method
[[MyObject class] respondsToSelector:@selector(myProperty)];
always returns NO.
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 ;)
Thanks in advance!
Alex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
[[MyObject class] respondsToSelector:...]
询问元对象是否响应该选择器。因此,实际上,它询问是否存在具有该选择器的类方法。如果您有以下情况,您的代码将返回 YES:它返回 NO,因为您具有与实例方法等效的方法:
您需要在类的实例上调用
respondsToSelector:
。您通常可以直接在元类上使用
instancesRespondToSelector:
(因此,[MyObjectinstancesRespondToSelector:...]
),但 Core Data 仅在您创建对象时综合相关方法实现,所以这是不可能的。但是,您可以通过正常的NSEntityDescription
路由创建一个实例,并在其上测试respondsToSelector:
。由于它都是核心数据,因此另一种方法是通过其
entitiesByName
字典向NSManagedObjectModel
询问相关的NSEntityDescription
并检查实体描述的propertiesByName
字典。[[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:It returns NO because you have the equivalent of the instance method:
You need to call
respondsToSelector:
on an instance of your class.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 normalNSEntityDescription
route and testrespondsToSelector:
on that.Since it's all Core Data, an alternative would be to ask the
NSManagedObjectModel
for the relevantNSEntityDescription
via itsentitiesByName
dictionary and inspect the entity description'spropertiesByName
dictionary.我唯一需要这样做的情况是动态设置事物,所以我只寻找设置器。我只是为设置器编写签名,然后测试它是否存在,然后使用它。
此代码满足了您可能无法消化字典中收到的所有数据的需求。
在本例中,它是稀疏的 json,因此某些数据可能并不总是存在于 json 中,因此单步遍历 myObjects 属性来查找其相应的键只会浪费大量精力。
The only cases I've required this has been to set things dynamically so I am only looking for the setter. I am just composing the signature for the setter and then testing that it exists and then using it.
This code satisfies a need where you may not be digesting all the data you receive in the dictionary.
In this case it was sparse json, so some data may not always exist in the json so stepping thru myObjects attributes looking for their corresponding key would just be a lot of wasted effort.
您正在综合类文件中的属性吗?
Are you synthesizing the property in the class file?