Skip to content

Instantly share code, notes, and snippets.

@janodev
Created September 8, 2011 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janodev/1202873 to your computer and use it in GitHub Desktop.
Save janodev/1202873 to your computer and use it in GitHub Desktop.
Describing an object using introspection
+(NSString*) describe:(id) object {
NSMutableString *string = [NSMutableString stringWithString:@""];
unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList([object 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(object, sel)]];
break;
case 'i':
[string appendString:[NSString stringWithFormat:@"%s : %i\n",
property_getName(properties[i]), objc_msgSend(object, sel)]];
break;
case 'f':
[string appendString:[NSString stringWithFormat:@"%s : %f\n",
property_getName(properties[i]), objc_msgSend(object, sel)]];
break;
// See "Property Attribute Description Examples" to add other types.
// http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
// Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW5
default:
break;
}
}
free(properties);
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment