Created
September 8, 2011 07:47
-
-
Save janodev/1202873 to your computer and use it in GitHub Desktop.
Describing an object using introspection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+(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