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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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... ;)
you need free(properties) at the end.
@JohnBiesnecker stringWithCString: is deprecated. I'm using stringWithCString:encoding: with NSUTF8StringEncoding encoding now. Just a note. :)
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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.