之前寫了給文章寫了給數(shù)據(jù)中數(shù)組里數(shù)據(jù)自動(dòng)轉(zhuǎn)成Model類的文章http://www.reibang.com/p/f86795aa7b09
剛剛有想了想寫了一個(gè)Model類屬性自動(dòng)賦值的
怕麻煩直接分享代碼--注釋寫的挺多的
/**
將字典中的屬性自動(dòng)賦值到Model類中
@param dic 數(shù)據(jù)字典
@param removeNames 不需要自動(dòng)賦值的類
@param namesDic 轉(zhuǎn)換屬性名字字典@{屬性名字:在數(shù)據(jù)中對(duì)應(yīng)名字}
*/
-(void)changing_properties:(NSDictionary *)dic removePropertys:(NSArray<NSString *> *)removeNames beChangeObjNames:(NSDictionary *)namesDic;
//方法實(shí)現(xiàn)
-(void)changing_properties:(NSDictionary *)dic removePropertys:(NSArray<NSString *> *)removeNames beChangeObjNames:(NSDictionary *)namesDic{
NSMutableArray *allNames = [[self getAllProperties] mutableCopy];//獲取屬性列表
//移除用戶要?jiǎng)h除的屬性
if (removeNames != nil && removeNames.count != 0) {
[allNames removeObjectsInArray:removeNames];
}
//將屬性賦值 主要用performSelector調(diào)用set方法
[allNames enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
///準(zhǔn)備方法名字
NSString *functionName = [NSString stringWithFormat:@"set%@:", [self changeFirstCharBig:obj]];
SEL selector = NSSelectorFromString(functionName);
///準(zhǔn)備屬性對(duì)應(yīng)value
NSString * objContent = @"";
//判斷屬性字段在數(shù)據(jù)字典中有沒有對(duì)應(yīng)的值,沒有的話調(diào)用屬性名轉(zhuǎn)化數(shù)組替換屬性名字
if ([namesDic objectForKey:obj] == nil) {
objContent = [dic objectForKey:obj];
}else{
// NSAssert([namesDic objectForKey:obj] != nil, @"屬性名字轉(zhuǎn)化錯(cuò)誤或數(shù)據(jù)中沒有該字段");
objContent = [dic objectForKey:[namesDic objectForKey:obj]];
}
///調(diào)用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];
}