How to get the class name of the nil property of the Objective-C class

In Objective-C, if the value of a property nilusing [obj.property class]returns nil. Is there a way to get the class name of the nil property of the Objective-C class?

Here is a very simple example:

#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");
    }
}

Conclusion class (null), NO

+5
source share
1 answer

How about checking the return type of the recipient?

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

Edit: to get the actual name of the class, inherit the property itself (code taken from 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);
+7
source

All Articles