2

Is there a way to automatically return an NSDictionary of all the (public) properties in a class? You can assume all properties are property lists and that I don't want to just hand over a pointer to the class itself. Any existing magic that can pull this off?

I know I can lazy instantiate an NSDictionary and manually fill it with properties in the getter.

Patrick Borkowicz
  • 1,206
  • 10
  • 19

1 Answers1

7

It's easy to get an array of declared properties using the class_copyPropertyList and property_getName functions in the Objective-C runtime. Here's one such implementation:

- (NSArray *)properties
{
    NSMutableArray *propList = [NSMutableArray array];
    unsigned int numProps = 0;
    unsigned int i = 0;

    objc_property_t *props = class_copyPropertyList([TestClass class], &numProps);
    for (i = 0; i < numProps; i++) {
        NSString *prop = [NSString stringWithUTF8String:property_getName(props[i])];
        [propList addObject:prop];
    }

    return [[propList copy] autorelease];
}

You could add this as a method in a category on NSObject. Here's a full code listing that can be compiled that demonstrates this.

I'm not sure how'd you do it with an NSDictionary, only because I'm not sure what you expect the key-value pairs to be.

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • Note that this won't necessarily work properly if the property has a custom getter assigned. You'll need to use [property_getAttributes](http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW6) to find if and what that is, for each property. – Wade Tregaskis Nov 20 '12 at 06:09
  • similar question: http://stackoverflow.com/questions/754824/get-an-object-attributes-list-in-objective-c Also be sure to import the objective-c runtime #import – Patrick Borkowicz Nov 29 '12 at 02:51