priore

Convert NSObject to NSDictionary

Jun 23rd, 2014
1,278
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // NSArray+NSDictionary.m
  2.  
  3. #import "NSObject+NSDictionary.h"
  4.  
  5. @implementation NSArray (NSDictionary)
  6.  
  7. - (NSDictionary*)toDictionary
  8. {
  9.     NSMutableDictionary *dict = [NSMutableDictionary new];
  10.     [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  11.         [dict setObject:[obj toDictionary] forKey:@(idx)];
  12.     }];
  13.    
  14.     return dict;
  15. }
  16.  
  17. @end
  18.  
  19. // NSObject+NSDictionary.m
  20.  
  21. #import <objc/runtime.h>
  22. @implementation NSObject (NSDictionary)
  23.  
  24. - (NSDictionary *)toDictionary {
  25.    
  26.     unsigned int count = 0;
  27.    
  28.     NSMutableDictionary *dictionary = [NSMutableDictionary new];
  29.     objc_property_t *properties = class_copyPropertyList([self class], &count);
  30.    
  31.     for (int i = 0; i < count; i++) {
  32.  
  33.         NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
  34.         id value = [self valueForKey:key];
  35.        
  36.         if (value == nil) {
  37.             // nothing todo
  38.         }
  39.         else if ([value isKindOfClass:[NSNumber class]]
  40.             || [value isKindOfClass:[NSString class]]
  41.             || [value isKindOfClass:[NSDictionary class]]) {
  42.         // TODO: extend to other types
  43.             [dictionary setObject:value forKey:key];
  44.         }
  45.         else if ([value isKindOfClass:[NSObject class]]) {
  46.             [dictionary setObject:[value toDictionary] forKey:key];
  47.         }
  48.         else {
  49.             NSLog(@"Invalid type for %@ (%@)", NSStringFromClass([self class]), key);
  50.         }
  51.     }
  52.    
  53.     free(properties);
  54.    
  55.     return dictionary;
  56. }
  57.  
  58. @end
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×