如何在Objective-C中检测属性返回类型 [英] How to detect a property return type in 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?
推荐答案
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:
@interface MyClass
{
NSArray * stuff;
}
@property (retain) NSArray * stuff;
@end
使用XML进行编码的方式如下:
Which gets encoded in XML something like this:
<class>
<name>MyClass</name>
<key>stuff</key>
</class>
根据这些信息,您想重新创建该类,并为它指定一个合适的stuff
值.
From this information, you want to recreate the class and also give it an appropriate value for stuff
.
这是它的外观:
#import <objc/runtime.h>
// ...
Class objectClass; // read from XML (equal to MyClass)
NSString * accessorKey; // read from XML (equals @"stuff")
objc_property_t theProperty =
class_getProperty(objectClass, accessorKey.UTF8String);
const char * propertyAttrs = property_getAttributes(theProperty);
// at this point, propertyAttrs is equal to: T@"NSArray",&,Vstuff
// thanks to Jason Coco for providing the correct string
// ... code to assign the property based on this information
Apple的文档(上面有链接)包含有关您可能希望在propertyAttrs
中看到的内容的所有肮脏细节.
Apple's documentation (linked above) has all of the dirty details about what you can expect to see in propertyAttrs
.
这篇关于如何在Objective-C中检测属性返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!