Forked from HeshamMegid/NSObject+NSDictionaryRepresentation.h
Created
February 1, 2013 16:34
-
-
Save PMUNOZ08/4692422 to your computer and use it in GitHub Desktop.
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 <Foundation/Foundation.h> | |
| @interface NSObject (NSDictionaryRepresentation) | |
| /** | |
| Returns an NSDictionary containing the properties of an object that are not nil. | |
| */ | |
| - (NSDictionary *)dictionaryRepresentation; | |
| @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
| #import "NSObject+NSDictionaryRepresentation.h" | |
| #import <objc/runtime.h> | |
| @implementation NSObject (NSDictionaryRepresentation) | |
| - (NSDictionary *)dictionaryRepresentation { | |
| unsigned int count = 0; | |
| // Get a list of all properties in the class. | |
| objc_property_t *properties = class_copyPropertyList([self class], &count); | |
| NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:count]; | |
| for (int i = 0; i < count; i++) { | |
| NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])]; | |
| NSString *value = [self valueForKey:key]; | |
| // Only add to the NSDictionary if it's not nil. | |
| if (value) | |
| [dictionary setObject:value forKey:key]; | |
| } | |
| free(properties); | |
| return dictionary; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment