5

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.

John Biesnecker
  • 3,782
  • 2
  • 34
  • 43

2 Answers2

9

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
  • 3,782
  • 2
  • 34
  • 43
  • 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 Dec 17 '09 at 13:23
  • you need free(properties) at the end. – eugene Jan 18 '13 at 03:11
  • 1
    @JohnBiesnecker `stringWithCString:` is deprecated. I'm using `stringWithCString:encoding:` with `NSUTF8StringEncoding` encoding now. Just a note. :) – Dean Kelly Oct 20 '14 at 19:58
2

dont forget

free(properties);

after the loop or you will get a leak. The apple documentation is clear:

An array of pointers of type objc_property_t describing the properties declared by the class. Any properties declared by superclasses are not included. The array contains *outCount pointers followed by a NULL terminator. You must free the array with free().

roberto.buratti
  • 2,487
  • 1
  • 16
  • 10