如何获取Objective-C类的nil属性的类名

bej*_*bee 5 reflection objective-c

在Objective-C中,如果属性值正在nil使用[obj.property class]返回nil.有没有办法获取Objective-C类的nil属性的类名?

这是一个非常简单的例子:

#import <Foundation/Foundation.h>

@interface MyClass : NSObject

@property (nonatomic, assign) NSDictionary *dict;

@end

@implementation MyClass

@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        MyClass *c = [[MyClass alloc] init];
        NSLog(@"class %@, %@", [c.dict class], [c.dict isKindOfClass:[NSDictionary class]] ? @"YES" : @"NO");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是 class (null), NO

小智 7

如何检查吸气剂的返回类型?

Method m = class_getInstanceMethod([MyClass class], @selector(somePropertyGetter));
char type[32];
method_getReturnType(m, type, sizeof(type));
printf("Property type: %s\n", type);
Run Code Online (Sandbox Code Playgroud)

编辑:获取实际的类名,内省属性本身(从此类别中获取的代码):

objc_property_t p = class_getProperty([MyClass class], "property");
// If you have a selector:
objc_property_t p = class_getProperty([MyClass class], sel_getName(someSelector));
const char *typeStr = property_getTypeString(p);
Run Code Online (Sandbox Code Playgroud)