Objective-C Quickie : Printing all declared properties of an object

Here’s some quick code that will print the values of all declared properties of an object using some of the introspection features of the runtime. This assumes that you’re using the default getter and setter names:


- (NSString *)description
{
    NSMutableString *string = [NSMutableString stringWithString:@""];
    unsigned int propertyCount;
    objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);
    
    for (unsigned int i = 0; i < propertyCount; i++)
    {
        NSString *selector = [NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding] ;
        
        SEL sel = sel_registerName([selector UTF8String]);
        
        const char *attr = property_getAttributes(properties[i]);
        switch (attr[1]) {
            case '@':
                [string appendString:[NSString stringWithFormat:@"%s : %@\n", property_getName(properties[i]), objc_msgSend(self, sel)]];
                break;
            case 'i':
                [string appendString:[NSString stringWithFormat:@"%s : %i\n", property_getName(properties[i]), objc_msgSend(self, sel)]];
                break;
            case 'f':
                [string appendString:[NSString stringWithFormat:@"%s : %f\n", property_getName(properties[i]), objc_msgSend(self, sel)]];
                break;
            default:
                break;
        }
    }
    
    free(properties);
    
    return string;

}

As you can see, I’m using this so that NSLog will give me something meaningful by overriding the description method of NSObject.
Edit: If you call this from a subclass, this method will only print the properties of the declared type!

Advertisements

Posted on April 14, 2011, in Code and tagged , , . Bookmark the permalink. 6 Comments.

  1. I certainly look forward to apps that crash spontaneously in debug logging because some random object happens to keep reference to an object that keeps reference back to it and you blow out the stack.

  1. Pingback: Property printing at Under The Bridge

  2. Pingback: Jeff LaMarche on the runtime and properties « Pat Zearfoss

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: