在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");
}
}
输出为class (null), NO
答案 0 :(得分:7)
如何检查getter的返回类型?
Method m = class_getInstanceMethod([MyClass class], @selector(somePropertyGetter));
char type[32];
method_getReturnType(m, type, sizeof(type));
printf("Property type: %s\n", type);
编辑:获取实际的类名,内省属性本身(代码取自this category):
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);