如何获取NSObject属性名和属性值的字典


    最近在利用SBJSON开发的过程中,发现SBJSON无法支持自定义的对象,为此考虑到了两种实现方案。一种在SBJSON框架一层实现一个自定义对象的Category以支持proxyForJson的方法。另一种方案就是应用层将自定义对象转换成属性名和属性值的字典后再交由SBJSON处理。鉴于本次SBJSON由一个底层库维护,折中方案就是在应用层进行自定义对象的处理。经过一番调查和搜索后,发现如下的实现方法:

  1. #import <Foundation/Foundation.h>   
  2. #import <objc/runtime.h>   
  3.  
  4. @interface NSObject (PropertyListing)   
  5.  
  6. // aps suffix to avoid namespace collsion   
  7. //   ...for Andrew Paul Sardone   
  8. - (NSDictionary *)properties_aps;   
  9.  
  10. @end   
  11.  
  12. @implementation NSObject (PropertyListing)   
  13.  
  14. - (NSDictionary *)properties_aps {   
  15.     NSMutableDictionary *props = [NSMutableDictionary dictionary];   
  16.     unsigned int outCount, i;   
  17.     objc_property_t *properties = class_copyPropertyList([self class], &outCount);   
  18.     for (i = 0; i &lt; outCount; i++) {   
  19.         objc_property_t property = properties[i];   
  20.         NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property)] autorelease];   
  21.         id propertyValue = [self valueForKey:(NSString *)propertyName];   
  22.         if (propertyValue) [props setObject:propertyValue forKey:propertyName];   
  23.     }   
  24.     free(properties);   
  25.     return props;   
  26. }   
  27.  
  28. @end 

    利用一些JSON框架进行自定义对象传输时处理如下:

    1. // The Person class has `firstName` and `lastName`   
    2. // properties.   
    3. // andrew is a Person instance with NSString values   
    4. // of "Andrew" and "Sardone" for `firstName` and   
    5. // `lastName` respectively.   
    6.  
    7. NSString *jsonString = [[andrew properties_aps]   
    8.                          JSONRepresentation];   
    9.  
    10. // now `jsonString` looks like:   
    11. //     { "firstName": "Andrew", "lastName": "Sardone" }  
posted @ 2013-05-16 15:32  @空空@  阅读(382)  评论(0编辑  收藏  举报