How to detect a property return type in Objective-C How to detect a property return type in Objective-C objective-c objective-c

How to detect a property return type in Objective-C


You're talking about runtime property introspection, which happens to be something that Objective-C is very good at.

In the case you describe, I'm assuming you have a class like this:

@interface MyClass{    NSArray * stuff;}@property (retain) NSArray * stuff;@end

Which gets encoded in XML something like this:

<class>    <name>MyClass</name>    <key>stuff</key></class>

From this information, you want to recreate the class and also give it an appropriate value for stuff.

Here's how it might look:

#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

Apple's documentation (linked above) has all of the dirty details about what you can expect to see in propertyAttrs.


The preferred way is to use the methods defined in the NSObject Protocol.

Specifically, to determine if something is either an instance of a class or of a subclass of that class, you use -isKindOfClass:. To determine if something is an instance of a particular class, and only that class (ie: not a subclass), use -isMemberOfClass:

So, for your case, you'd want to do something like this:

// Using -isKindOfClass since NSMutableArray subclasses should probably// be handled by the NSMutableArray code, not the NSArray codeif ([anObject isKindOfClass:NSMutableArray.class]) {    // Stuff for NSMutableArray here} else if ([anObject isKindOfClass:NSArray.class]) {    // Stuff for NSArray here    // If you know for certain that anObject can only be    // an NSArray or NSMutableArray, you could of course    // just make this an else statement.}