Last active
March 19, 2021 22:59
-
-
Save dzenbot/3ba254f80d411d6cbad4 to your computer and use it in GitHub Desktop.
Useful for printing custom property values on an NSObject subclass
This file contains hidden or 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
#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