字典转模型,模型转字典

//字典转模型

- (id)initWithDictionary:(NSDictionary*)dic{

self= [superinit];

if(self){

for(NSString*keyin[dicallKeys]) {

idvalue = dic[key];

//生成setter方法

SELsel = [selfpropertitySetterByKey:key];

if(sel){

((void(*)(id,SEL,id))objc_msgSend)(self,sel,value);

}

}

}

returnself;

}

//生成setter方法

- (SEL)propertitySetterByKey:(NSString*)key{

NSString*propertitySetter = [NSStringstringWithFormat:@"set%@:",key.capitalizedString];

SELsel =NSSelectorFromString(propertitySetter);

if([selfrespondsToSelector:sel]){

returnsel;

}

returnnil;

}


//model转字典

- (NSDictionary*)covertToDictionary{

NSMutableDictionary*dic = [@{}mutableCopy];

unsignedintcount =0;

objc_property_t*propertities =class_copyPropertyList([selfclass], &count);

for(NSIntegeri=0; i

constchar*properKey =property_getName(propertities[i]);

NSString*proName = [NSStringstringWithUTF8String:properKey];

//生成getter方法

SELsel = [selfpropertityGetterByKey:proName];

if(sel){

idvalue = ((id(*)(id,SEL))objc_msgSend)(self,sel);

if(value){

dic[proName] = value;

}else{

dic[proName] =@"该值为空";

}

}

}

returndic;

}

//生成getter方法

- (SEL)propertityGetterByKey:(NSString*)key{

SELsel =NSSelectorFromString(key);

if([selfrespondsToSelector:sel]){

returnsel;

}

returnnil;

}


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

推荐阅读更多精彩内容