Skip to content

Instantly share code, notes, and snippets.

@thefotes
Created April 22, 2015 13:54
Show Gist options
  • Save thefotes/e639c3ae1f4d0ce36d24 to your computer and use it in GitHub Desktop.
Save thefotes/e639c3ae1f4d0ce36d24 to your computer and use it in GitHub Desktop.
Returns dictionary with property names as keys, and their values as the object
// NSObject+PropertyDictionary.m
//
// Created by Peter Foti on 4/22/15.
#import "NSObject+PropertyDictionary.h"
#import <objc/runtime.h>
@implementation NSObject (PropertyDictionary)
- (NSDictionary *)toDictionary
{
unsigned int outCount;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propertyName = property_getName(property);
NSString *propertyString = [NSString stringWithUTF8String:propertyName];
dict[propertyString] = [self valueForKey:propertyString];
}
return [NSDictionary dictionaryWithDictionary:dict];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment