Skip to content

Instantly share code, notes, and snippets.

@dzenbot
Last active March 19, 2021 22:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzenbot/3ba254f80d411d6cbad4 to your computer and use it in GitHub Desktop.
Save dzenbot/3ba254f80d411d6cbad4 to your computer and use it in GitHub Desktop.
Useful for printing custom property values on an NSObject subclass
#import "NSObject+SmartDescription.h"
#import <objc/runtime.h>
@implementation NSObject (SmartDescription)
- (NSString *)smartDescription
{
NSMutableString *string = [NSMutableString stringWithFormat:@"<%@: %p> ", NSStringFromClass([self class]), self];
NSDictionary *properties = [self propertyList];
for (int i = 0; i < properties.count; i++) {
if (i != 0) {
[string appendString:@" | "]; // Separator
}
NSString *key = [properties allKeys][i];
[string appendFormat:@"%@ = %@", key, properties[key]];
}
return string;
}
- (NSDictionary *)propertyList
{
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) encoding:NSUTF8StringEncoding];
id propertyValue = [self valueForKey:(NSString *)propertyName];
if (propertyValue) [props setObject:propertyValue forKey:propertyName];
}
free(properties);
return props;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment