Skip to content

Instantly share code, notes, and snippets.

@bryanluby
Created May 6, 2014 01:04
Show Gist options
  • Save bryanluby/a53ca5d43c7406654791 to your computer and use it in GitHub Desktop.
Save bryanluby/a53ca5d43c7406654791 to your computer and use it in GitHub Desktop.
NSObject category for describing the keys and values of an object.
//
// 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
//
// 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