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

如何获取NSObject属性名和属性值的字典
2011-03-03 12:04:06
标签:JSON 自定义对象 休闲 职场

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

import <Foundation/Foundation.h>

import <objc/runtime.h>

@interface NSObject (PropertyListing)

// aps suffix to avoid namespace collsion
// ...for Andrew Paul Sardone

  • (NSDictionary *)properties_aps;

@end

@implementation NSObject (PropertyListing)

  • (NSDictionary *)properties_aps {
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property)] autorelease];
    id propertyValue = [self valueForKey:(NSString *)propertyName];
    if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return props;
    }

@end
利用一些JSON框架进行自定义对象传输时处理如下:
// The Person class has firstName and lastName
// properties.
// andrew is a Person instance with NSString values
// of "Andrew" and "Sardone" for firstName and
// lastName respectively.

NSString *jsonString = [[andrew properties_aps]
JSONRepresentation];

// now jsonString looks like:
// { "firstName": "Andrew", "lastName": "Sardone" }

代码链接: http://forrst.com/posts/Getting_a_dictionary_of_an_NSObjects_property_n-h2T

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容