Created
May 6, 2014 01:04
-
-
Save bryanluby/a53ca5d43c7406654791 to your computer and use it in GitHub Desktop.
NSObject category for describing the keys and values of an object.
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
// | |
// NSObject+LUBDescription.h | |
// | |
// Created by Bryan Luby on 5/5/14. | |
// Copyright (c) 2014 Bryan Luby. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSObject (LUBDescription) | |
///Returns a dictionary description of all property keys and values for an object. | |
- (NSString *)lub_description; | |
@end |
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
// | |
// NSObject+LUBDescription.m | |
// | |
// Created by Bryan Luby on 5/5/14. | |
// Copyright (c) 2014 Bryan Luby. All rights reserved. | |
// | |
#import "NSObject+LUBDescription.h" | |
#import <objc/runtime.h> | |
@implementation NSObject (LUBDescription) | |
- (NSString *)lub_description | |
{ | |
NSMutableDictionary *stateDictionary = [NSMutableDictionary dictionary]; | |
Class aClass = [self class]; | |
while (aClass != [NSObject class]) { | |
unsigned int propertyCount = 0; | |
objc_property_t *properties = class_copyPropertyList(aClass, &propertyCount); | |
if (propertyCount) { | |
for (int i = 0; i < propertyCount; i++) { | |
objc_property_t property = properties[i]; | |
@try { | |
NSString *propertyKey = [NSString stringWithUTF8String:property_getName(property)]; | |
stateDictionary[propertyKey] = [self valueForKey:propertyKey]; | |
} @catch (NSException *exception) {} | |
} | |
} | |
free(properties); | |
aClass = [aClass superclass]; | |
} | |
return [[stateDictionary copy] description]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment