Patrick Borkowicz
Patrick Borkowicz

Reputation: 1216

Put all object properties into an NSDictionary or NSArray

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.

Upvotes: 2

Views: 927

Answers (1)

mipadi
mipadi

Reputation: 411310

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.

Upvotes: 7

Related Questions