美文网首页
轻量极字典转modle

轻量极字典转modle

作者: 牛1688 | 来源:发表于2017-02-16 08:17 被阅读0次

#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

相关文章

网友评论

      本文标题:轻量极字典转modle

      本文链接:https://www.haomeiwen.com/subject/vhpcwttx.html