Created
November 12, 2014 11:17
-
-
Save priore/3a0bafd04f2e9f0da3c6 to your computer and use it in GitHub Desktop.
Convert NSObject to NSDictionary
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
| // NSArray+NSDictionary.m | |
| #import "NSObject+NSDictionary.h" | |
| @implementation NSArray (NSDictionary) | |
| - (NSDictionary*)toDictionary | |
| { | |
| NSMutableDictionary *dict = [NSMutableDictionary new]; | |
| [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { | |
| [dict setObject:[obj toDictionary] forKey:@(idx)]; | |
| }]; | |
| return dict; | |
| } | |
| @end | |
| // NSObject+NSDictionary.m | |
| #import <objc/runtime.h> | |
| @implementation NSObject (NSDictionary) | |
| - (NSDictionary *)toDictionary { | |
| unsigned int count = 0; | |
| NSMutableDictionary *dictionary = [NSMutableDictionary new]; | |
| objc_property_t *properties = class_copyPropertyList([self class], &count); | |
| for (int i = 0; i < count; i++) { | |
| NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])]; | |
| id value = [self valueForKey:key]; | |
| if (value == nil) { | |
| // nothing todo | |
| } | |
| else if ([value isKindOfClass:[NSNumber class]] | |
| || [value isKindOfClass:[NSString class]] | |
| || [value isKindOfClass:[NSDictionary class]]) { | |
| // TODO: extend to other types | |
| [dictionary setObject:value forKey:key]; | |
| } | |
| else if ([value isKindOfClass:[NSObject class]]) { | |
| [dictionary setObject:[value toDictionary] forKey:key]; | |
| } | |
| else { | |
| NSLog(@"Invalid type for %@ (%@)", NSStringFromClass([self class]), key); | |
| } | |
| } | |
| free(properties); | |
| return dictionary; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment