之前写了给文章写了给数据中数组里数据自动转成Model类的文章http://www.jianshu.com/p/f86795aa7b09
刚刚有想了想写了一个Model类属性自动赋值的
怕麻烦直接分享代码--注释写的挺多的
/**
将字典中的属性自动赋值到Model类中
@param dic 数据字典
@param removeNames 不需要自动赋值的类
@param namesDic 转换属性名字字典@{属性名字:在数据中对应名字}
*/
-(void)changing_properties:(NSDictionary *)dic removePropertys:(NSArray<NSString *> *)removeNames beChangeObjNames:(NSDictionary *)namesDic;
//方法实现
-(void)changing_properties:(NSDictionary *)dic removePropertys:(NSArray<NSString *> *)removeNames beChangeObjNames:(NSDictionary *)namesDic{
NSMutableArray *allNames = [[self getAllProperties] mutableCopy];//获取属性列表
//移除用户要删除的属性
if (removeNames != nil && removeNames.count != 0) {
[allNames removeObjectsInArray:removeNames];
}
//将属性赋值 主要用performSelector调用set方法
[allNames enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
///准备方法名字
NSString *functionName = [NSString stringWithFormat:@"set%@:", [self changeFirstCharBig:obj]];
SEL selector = NSSelectorFromString(functionName);
///准备属性对应value
NSString * objContent = @"";
//判断属性字段在数据字典中有没有对应的值,没有的话调用属性名转化数组替换属性名字
if ([namesDic objectForKey:obj] == nil) {
objContent = [dic objectForKey:obj];
}else{
// NSAssert([namesDic objectForKey:obj] != nil, @"属性名字转化错误或数据中没有该字段");
objContent = [dic objectForKey:[namesDic objectForKey:obj]];
}
///调用set方法赋值
if ([self respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self performSelector:selector withObject:objContent];
#pragma clang diagnostic pop
}
}];
}
//获取该类的所有属性
-(NSArray *)getAllProperties{
unsigned int count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableArray * arr = [[NSMutableArray alloc]init];
for(int i = 0; i < count; i++){
objc_property_t property = properties[i];
[arr addObject:[NSString stringWithFormat:@"%s", property_getName(property)]];
}
free(properties);
return arr;
}
//将字符串首字母大写
-(NSString *)changeFirstCharBig:(NSString *)string{
NSString *upstring = [string uppercaseString];
string = [string substringFromIndex:1];
upstring = [upstring substringToIndex:1];
return [NSString stringWithFormat:@"%@%@", upstring, string];
}
网友评论