温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-04-21 13:42:07 阅读:6514 作者:benjielin 栏目:软件技术
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>


    最近在利用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 &lt; 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-h3T

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×