iOS开发之字典数据建立模型步骤

 

 

1. 在控制器属性的(questions)set方法中完成字典转模型的操作

- (NSArray *)questions

{

if (nil == _questions) {

//1.加载plist文件

NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions" ofType:@"plist"]];

//2.字典转模型

NSMutableArray *questionArray = [NSMutableArray array];

for (NSDictionary *dict in dictArray) {

CLQuestion *question = [CLQuestion questionWithDict:dict];

            [questionArray addObject:question];

        }

//3.赋值

_questions = questionArray;

    }

}

 

2.新建模型类CLQuestion

//2.1依据字典内容建立对应的成员变量

/** 答案*/

@property (nonatomic, copy) NSString *answer;

/** 图像名称*/

@property (nonatomic, copy) NSString *icon;

/** 题目*/

@property (nonatomic, copy) NSString *title;

/** 待选项*/

@property (nonatomic, strong) NSArray *options;

//2.2新建2个初始化方法,仿照系统写法 一个对象方法 一个类方法

- (instancetype)initWithDict:(NSDictionary *)dict;

+ (instancetype)questionWithDict:(NSDictionary *)dict;

//2.3在初始化方法中完成 依据字典内容对成员变量赋值 这里用KVC更简单

- (instancetype)initWithDict:(NSDictionary *)dict

{

if (self = [super init]) {

self.icon = dict[@"icon"];

self.title = dict[@"title"];

self.answer = dict[@"answer"];

self.options = dict[@"options"];

}

return self;

}

+ (instancetype)questionWithDict:(NSDictionary *)dict

{

return [[self alloc]initWithDict:dict];

}

 

3.在控制器中使用的方法

 

CLQuestion *question = self.questions[self.index];

iOS开发之字典数据建立模型步骤,布布扣,bubuko.com

iOS开发之字典数据建立模型步骤

上一篇:Android 强制横屏或竖屏注意事项及onConfigurationChanged的使用


下一篇:URAL1018 Binary Apple Tree(树dp)