Skip to content

Instantly share code, notes, and snippets.

@priore
Created November 12, 2014 11:17
Show Gist options
  • Save priore/3a0bafd04f2e9f0da3c6 to your computer and use it in GitHub Desktop.
Save priore/3a0bafd04f2e9f0da3c6 to your computer and use it in GitHub Desktop.
Convert NSObject to NSDictionary
// 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