views:

217

answers:

1

Is it possible to get an array of all of an object's properties in Objective C? Basically, what I want to do is something like this:

- (void)save {
   NSArray *propertyArray = [self propertyNames];
   for (NSString *propertyName in propertyArray) {
      [self doSomethingCoolWithValue:[self valueForKey:propertyName]];
   }
}

Is this possible? It seems like it should be, but I can't figure out what method my propertyNames up there should be.

+4  A: 

I did some more digging, and found what I wanted in the Objective-C Runtime Programming Guide. Here's how I've implemented the what I wanted to do in my original question, drawing heavily from Apple's sample code:

#import <Foundation/NSObjCRuntime.h>
#import <objc/runtime.h>

- (void)save {
    id currentClass = [self class];
    NSString *propertyName;
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);
    for (i = 0; i < outCount; i++) {
     objc_property_t property = properties[i];
     propertyName = [NSString stringWithCString:property_getName(property)];
     [self doSomethingCoolWithValue:[self valueForKey:propertyName]];
    }
}

I hope this will help someone else looking for a way to access the names of an object's properties programatically.

John Biesnecker
If you search for `class_copyPropertyList` this questions has been answered several times on StackOverflow in various forms, but unless you know the answer already, if hard to know what to search for... ;)
John Biesnecker