Eny*_*yra 19 types runtime properties objective-c key-value-observing
我在运行时在objective-c中有一个对象,我只知道KVC键,我需要检测此属性的返回值类型(例如,我需要知道它是NSArray还是NSMutableArray),我该怎么做呢?
e.J*_*mes 34
你在谈论运行时属性内省,这恰好是Objective-C 非常擅长的东西.
在你描述的情况下,我假设你有一个这样的类:
@interface MyClass
{
    NSArray * stuff;
}
@property (retain) NSArray * stuff;
@end
Run Code Online (Sandbox Code Playgroud)
哪个用XML编码,如下所示:
<class>
    <name>MyClass</name>
    <key>stuff</key>
</class>
Run Code Online (Sandbox Code Playgroud)
从这些信息中,您希望重新创建该类,并为其提供适当的值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
Run Code Online (Sandbox Code Playgroud)
Apple的文档(上面链接)包含了您可以期待看到的所有内容的详细信息propertyAttrs.