Getting a dictionary of an NSObject's property names and values

andrewsardone

Andrew Sardone

3 years ago · 3,524 views
#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface NSObject (PropertyListing)

// aps suffix to avoid namespace collsion
//   ...for Andrew Paul Sardone
- (NSDictionary *)properties_aps;

@end

@implementation NSObject (PropertyListing)

- (NSDictionary *)properties_aps {
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property)] autorelease];
        id propertyValue = [self valueForKey:(NSString *)propertyName];
        if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return props;
}

@end
Raw

Randomly had an idea to see if there was an easy way to list all the declared properties for a given object.

I could see this being useful (if tweaked a little) for sending along a JSON representation of an object that had simple properties (via the json-framework).

// The Person class has `firstName` and `lastName` 
// properties.
// andrew is a Person instance with NSString values 
// of "Andrew" and "Sardone" for `firstName` and 
// `lastName` respectively.

NSString *jsonString = [[andrew properties_aps] 
                         JSONRepresentation];

// now `jsonString` looks like:
//     { "firstName": "Andrew", "lastName": "Sardone" }
Raw

(originally posted this snippet on Github's gist)

Tagged: objective-c
Comments are only visible to Forrst members. Log in or Request an invite.
3 new notifications