如何检测 Objective-C 中的属性返回类型
我在运行时在 Objective-C 中有一个对象,我只知道 KVC 键,并且我需要检测该属性的返回值类型(例如,我需要知道它是 NSArray 还是 NSMutableArray),我该怎么做?
I have an object in objective-c at runtime, from which I only know the KVC key and I need to detect the return value type (e.g. I need to know if its an NSArray or NSMutableArray) of this property, how can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您正在谈论运行时属性自省,这恰好是 Objective-C 的东西 非常擅长。
在您描述的情况下,我假设您有一个像这样的类:
它在 XML 中进行编码,如下所示:
根据此信息,您想要重新创建该类,并为它提供适当的值
stuff.
它可能是这样的:
Apple 的文档(上面链接)包含了您可以在
propertyAttrs
中看到的所有肮脏细节。You're talking about runtime property introspection, which happens to be something that Objective-C is very good at.
In the case you describe, I'm assuming you have a class like this:
Which gets encoded in XML something like this:
From this information, you want to recreate the class and also give it an appropriate value for
stuff
.Here's how it might look:
Apple's documentation (linked above) has all of the dirty details about what you can expect to see in
propertyAttrs
.便宜的答案:使用此处的 NSObject+Properties 源。
它实现了与上述相同的方法。
Cheap answer: use the NSObject+Properties source here.
It implements the same methodology described above.
首选方法是使用 NSObject 协议。
具体来说,要确定某物是某个类的实例还是该类的子类的实例,请使用
-isKindOfClass:
。 要确定某物是否是特定类的实例,并且只是该类(即:不是子类),请使用-isMemberOfClass:
因此,对于您的情况,您需要执行以下操作:
The preferred way is to use the methods defined in the NSObject Protocol.
Specifically, to determine if something is either an instance of a class or of a subclass of that class, you use
-isKindOfClass:
. To determine if something is an instance of a particular class, and only that class (ie: not a subclass), use-isMemberOfClass:
So, for your case, you'd want to do something like this:
这实际上是针对 Greg Maletic 为回应 e.James 21APR09 提供的答案而提出的问题的评论。
同意 Objective-C 可以使用更好的实现来获取这些属性。
下面是我快速组合起来检索单个对象属性的属性的方法:
属性键的部分列表:
完整列表位于 苹果
This is really a comment addressing an issue raised by Greg Maletic in response to answer provided by e.James 21APR09.
Agreed that Objective-C could use a better implementation for getting these attributes.
Below is a method I quickly threw together to retrieve attributes of a single object property:
Partial list of attribute keys:
Full list at Apple
您可以使用 isKindOfClass 消息
You can use isKindOfClass message
如果您知道该属性已定义:
并与 isKindOfClass、isSubClass 等进行比较。
If you know that the property is defined :
And compare with isKindOfClass, isSubClass, etc.