字典转模型实现方法如下:
#import "MJApp.h"@implementation MJApp- (instancetype)initWithDict:(NSDictionary *)dict{ if (self = [super init]) { self.name = dict[@"name"]; self.icon = dict[@"icon"]; self.title = dict[@"title"]; self.answer = dict[@"answer"]; } return self;}+ (instancetype)appWithDict:(NSDictionary *)dict{ return [[self alloc] initWithDict:dict];}@end
或者用KVC方法来实现
#import "MJApp.h"@implementation MJApp- (instancetype)initWithDict:(NSDictionary *)dict{ if (self = [super init]) { [self setValuesForKeysWithDictionary:dict]; } return self;}+ (instancetype)appWithDict:(NSDictionary *)dict{ return [[self alloc] initWithDict:dict];}@end
但是KVC的使用是有条件的 ; 由于KVC会将字典所有的键值对(key-value)赋值给模型对应的属性.只有当字典的键值对个数跟模型的属性个数相等,并且属性名必须和字典的键值对一样时才可以使用KVC.
/** * 字典转模型,模型再次存入数组中 重写数组的set方法 */
-(NSArray *)questions{
if (_questions ==nil) { //加载plist,将plist中存储的字典数据放在数组dictArray中
NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];
NSMutableArray *questionArray = [NSMutableArray array]; //用自定义的JNQuestion模型question来接收 数组 dictArray 中的元素;
for (NSDictionary * dict in dictArray){
JNQuestions *question = [JNQuestions questionWithDict:dict]; //JNQuestions *question =[[JNQuestions alloc]initWithDict:dict];
[questionArray addObject:question];}
// 赋值
_questions = questionArray;
} return _questions;
}