[轉(zhuǎn)]如何獲取NSObject屬性名和屬性值的字典

如何獲取NSObject屬性名和屬性值的字典
2011-03-03 12:04:06
標(biāo)簽:JSON 自定義對(duì)象 休閑 職場(chǎng)

最近在利用SBJSON開(kāi)發(fā)的過(guò)程中,發(fā)現(xiàn)SBJSON無(wú)法支持自定義的對(duì)象,為此考慮到了兩種實(shí)現(xiàn)方案。一種在SBJSON框架一層實(shí)現(xiàn)一個(gè)自定義對(duì)象的Category以支持proxyForJson的方法。另一種方案就是應(yīng)用層將自定義對(duì)象轉(zhuǎn)換成屬性名和屬性值的字典后再交由SBJSON處理。鑒于本次SBJSON由一個(gè)底層庫(kù)維護(hù),折中方案就是在應(yīng)用層進(jìn)行自定義對(duì)象的處理。經(jīng)過(guò)一番調(diào)查和搜索后,發(fā)現(xiàn)如下的實(shí)現(xiàn)方法:

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框架進(jìn)行自定義對(duì)象傳輸時(shí)處理如下:
// 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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容