Skip to content

Instantly share code, notes, and snippets.

@oscahie
Last active June 28, 2016 14:47
Show Gist options
  • Save oscahie/0730c938fa43749cbfff1806b47c7d37 to your computer and use it in GitHub Desktop.
Save oscahie/0730c938fa43749cbfff1806b47c7d37 to your computer and use it in GitHub Desktop.
Uses object introspection to print the list of properties and ivars of the instance, together with their current values when possible (i.e. when they are KVC compliant)
- (NSString *)osc_introspectiveDescription
{
// Loop through our superclasses until we hit NSObject
NSMutableArray *propertyList = [NSMutableArray array];
NSMutableArray *ivarList = [NSMutableArray array];
Class subclass = [self class];
while (subclass != [NSObject class])
{
unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList(subclass,&propertyCount);
for (int i = 0; i < propertyCount; i++)
{
// Add property name to array
objc_property_t property = properties[i];
const char *propertyName = property_getName(property);
[propertyList addObject:@(propertyName)];
}
free(properties);
unsigned int ivarCount;
Ivar* ivars = class_copyIvarList(subclass, &ivarCount);
for (unsigned int i = 0; i < ivarCount; ++i)
{
const char *ivarName = ivar_getName(ivars[i]);
[ivarList addObject:@(ivarName)];
}
free(ivars);
subclass = [subclass superclass];
}
NSMutableString *propertyDescriptions = [[NSMutableString alloc] init];
for (NSString *key in propertyList)
{
@try
{
id value = [self valueForKey:key];
[propertyDescriptions appendFormat:@"; %@ = %@\n", key, value];
}
@catch (NSException *exception)
{
[propertyDescriptions appendFormat:@"; %@ = N/A\n", key];
}
}
[propertyDescriptions appendString:@"-- ivars:\n"];
for (NSString *ivarName in ivarList)
{
@try
{
id value = [self valueForKey:ivarName];
[propertyDescriptions appendFormat:@"; %@ = %@\n", ivarName, value];
}
@catch (NSException *exception)
{
[propertyDescriptions appendFormat:@"; %@ = N/A\n", ivarName];
}
}
return [NSString stringWithFormat:@"<%@: 0x%lx\n%@>", [self class], (unsigned long)self, propertyDescriptions];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment