iOS開發中經常會用到Model,怎樣把字典轉化成Model呢?個人覺得用KVC是很方便的。。Demo地址
字典類型
#import "ViewController.h"
#import "PeopleModel.h"
@interface ViewController ()
@end
NSMutableDictionary *dic_per = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@12,@"id",
@"cfdfvd",@"name",
[NSNumber numberWithInt:10],@"age",
[NSNumber numberWithBool:YES],@"sex",
nil];
創建一個和字典對應的model 類 屬性名需要和字典的key 值一致,由於id 是預留字段我們無法添加一個名爲id 的屬性,現在先用userid 來代替它
#import <Foundation/Foundation.h>
@interface PersonModel : NSObject
@property(nonatomic, strong)NSNumber *userid;
@property(nonatomic, copy)NSString *name;
@property(nonatomic, assign)NSInteger age;
@property(nonatomic, assign)BOOL sex;
@property(nonatomic, assign)BOOL is select; // 除了字典中包含的字段外還可以根據需要自己在model 中添加需要的字段
@end
在PersonModel.h 中要聲明兩個方法
-(instancetype)initWithDic:(NSDictionary *)dic ;
+(instancetype)personObjectWithDic:(NSDictionary *)dic;
方法的實現
#import "PersonModel.h"
@implementation PersonModel
+(instancetype)personObjectWithDic:(NSDictionary *)dic{
PersonModel *model = [[self alloc]initWithDic:dic];
return model ;
}
-(instancetype)initWithDic:(NSDictionary *)dic{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dic];
}
// 自己在model中添加的字段無法通過setValuesForKeysWithDictionary 進行賦值要在初始化時定義初值
self.isselect = NO ;
return self ;
}
當你在外部調用personObjectWithDic:方法時內部會調用initWithDic 的方法返回一個model 對象
對於特殊字段的處理 實現以下方法
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
if ([key isEqualToString:@"id"]) {
self.userid = value ;
}
}
相關文章: