6

在 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

4

1 回答 1

8

检查 getter 的返回类型怎么样?

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

编辑:要获取实际的类名,请检查属性本身(取自该类别的代码):

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);
于 2013-03-05T19:17:55.277 回答