我直接在昨晚的model類中進(jìn)行代碼操作了狮辽。mac下面沒網(wǎng)絡(luò),只有手寫赖舟,諒解哈
# .m文件中
+ (instancetype)modelWithDict:(NSDictionary *)dict{
// 創(chuàng)建對應(yīng)類的對象
id objc =[[self alloc] init];
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList(self, &count);
// 遍歷
for (int i = 0; i< count; i++){
Ivar ivar = ivarList[i];
// 獲取成員名(獲取到的是C語言類型蓬戚,需要轉(zhuǎn)換為OC字符串)
NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivar)];
// 成員屬性類型
NSString *propertyType = [NSString stringWithUTF8String: ivar_getTypeEncoding(ivar)];
// 首先獲取key(根據(jù)你的propertyName 截取字符串)
NSString *key = [propertyName substringFromIndex:1];
// 獲取字典的value
id value = dict[key];
/**
這里根據(jù)值進(jìn)行判斷后面的元素是否存在字典
二級轉(zhuǎn)換:值是字典,成員屬性不是字典才需要轉(zhuǎn)換為模型
*/
if([value isKindOfClass:[NSDictonary Class]] && [propertyType containsString:@"NS"]){ // 需要字典轉(zhuǎn)換成模型
// 轉(zhuǎn)換成哪個(gè)類型
// 獲取的propertyType 樣式:@"@\"User\""
// 字符串的截取
NSRange range = [properType rangeOfString:@"\"]; // 第一個(gè) \
propertyType = [propertyType substringFromIndex:range.location + range.length];
range = [properType rangeOfString:@"\"]; // 第二個(gè) \
propertyType = [propertyType substringToIndex:range.location];
// 獲取需要轉(zhuǎn)換類的類對象
Class modelClass = NSClassFromString(propertyType);
if(modelClass){
value = [modelClass modelWithDict:value]; // 調(diào)用字典轉(zhuǎn)模型的方法
{
{
// 給模型的屬性賦值
// value : 字典的值
// key : 屬性名
if (value){ // 這里是因?yàn)镵VC賦值建蹄,不能為空
[objc setValue:value forKey:key];
}
NSLog(@"%@ %@",propertyType,propertyName);
}
NSLog(@"%zd",count); // 這里會(huì)輸出self中成員屬性的總數(shù)
return objc;
}