轻量极字典转modle

#import"NSObject+Extansion.h"

#import

#import"news.h"

@implementationNSObject (extansion)

+(instancetype)objcWithDict:(NSDictionary*)dict{

news* model = [[selfalloc]init];

//把模型所有属性包装成数组

NSArray* array = [selfloadModleArray];

for(NSString* strinarray) {

if(dict[str]!=nil) {

[modelsetValue:dict[str]forKeyPath:str];

}

}

returnmodel;

}

-(NSString*)description{

//把模型所有属性包装成数组

NSArray* array =[[selfclass]loadModleArray];

//模型转字典

NSDictionary* dict = [selfdictionaryWithValuesForKeys:array];

return[NSStringstringWithFormat:@"<%@:%p> %@",self.class,self,dict];

}

constchar* key ;

+(NSArray* )loadModleArray{

//获取关联对像

/*

参数1:就是本类==self;

参数2:void *就是任意的意思,可以用const charkey或const char * key ;

*/

NSArray* pry =objc_getAssociatedObject(self,key);

//pry有值时,后面的代码不再执行,可以提高效率

if(pry!=nil) {

returnpry;

}

////参数1:类

////参数2:属性指针计数

////取成员变量列表,swift用这个方法容易崩溃iu

//class_copyIvarList(__unsafe_unretained Class cls, unsigned int *outCount);

//

////取方法列表

//class_copyMethodList(__unsafe_unretained Class cls, unsigned int *outCount);

//

////取成员属性列表

//class_copyPropertyList(__unsafe_unretained Class cls, unsigned int *outCount);

//

////协协议列表

//class_copyProtocolList(__unsafe_unretained Class cls, unsigned int *outCount);

//获得属性列表

unsignedintoutCount =0;

objc_property_t* cty =class_copyPropertyList([selfclass], &outCount);

NSMutableArray* arrayM = [NSMutableArrayarrayWithCapacity:outCount];

for(unsignedinti =0;i < outCount; i++) {

//获取属性. c语言中没有对象不要用*

objc_property_tpty = cty[i];

//获取属性名字

constchar* name =property_getName(pty);

//转码后添加到数组

[arrayMaddObject:[NSStringstringWithUTF8String:name]];

}

free(cty);

//属性个总数

//设置关联对像.把获取到的数组当作一个属性设给他

objc_setAssociatedObject(self,key, arrayM,OBJC_ASSOCIATION_COPY_NONATOMIC);

returnarrayM;

}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,762评论 0 9
  • Objective-C语言是一门动态语言,它将很多静态语言在编译和链接时期做的事放到了运行时来处理。这种动态语言的...
    有一种再见叫青春阅读 607评论 0 3
  • 原文出处:南峰子的技术博客 Objective-C语言是一门动态语言,它将很多静态语言在编译和链接时期做的事放到了...
    _烩面_阅读 1,252评论 1 5
  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 2,231评论 0 7
  • 每个周五的晚上都会立flag,周六一定要睡到大中午,忙碌了一周,应该好好补补觉,可事与愿违,周六早上还是会在固定的...
    跑来跑去的强子阅读 452评论 0 0