模型.h文件
#import <Foundation/Foundation.h>
@interface LFQuestion : NSObject
@property (nonatomic, copy) NSString *answer;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, strong) NSArray *options;
@property (nonatomic, strong) UIImage *image;
/** 用字典实例化对象的成员方法 */
- (instancetype)initWithDict:(NSDictionary *)dict;
/** 用字典实例化对象的类方法,又称工厂方法 */
+ (instancetype)questionWithDict:(NSDictionary *)dict;
/** 从plist加载对象数组 */
+ (NSArray *)questions;
@end
模型.m文件
#import "LFQuestion.h"
@implementation LFQuestion
+ (instancetype)questionWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
self.answer = dict[@"answer"];
self.icon = dict[@"icon"];
self.title = dict[@"title"];
self.options = dict[@"options"];
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+ (NSArray *)questions
{
NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in array) {
[arrayM addObject:[LFQuestion questionWithDict:dict]];
}
return arrayM;
}
@end
二、 (KVC)的使用
(1)在模型内部的数据处理部分,可以使用键值编码来进行处理
- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
// self.answer = dict[@"answer"];
// self.icon = dict[@"icon"];
// self.title = dict[@"title"];
// self.options = dict[@"options"];
// KVC (key value coding)键值编码
// cocoa 的大招,允许间接修改对象的属性值
// 第一个参数是字典的数值
// 第二个参数是类的属性
[self setValue:dict[@"answer"] forKeyPath:@"answer"];
[self setValue:dict[@"icon"] forKeyPath:@"icon"];
[self setValue:dict[@"title"] forKeyPath:@"title"];
[self setValue:dict[@"options"] forKeyPath:@"options"];
}
return self;
}
(2)setValuesForKeys的使用
上述数据操作细节,可以直接通过setValuesForKeys方法来完成。
- (instancetype)initWithDict:(NSDictionary *)dict
{
self = [super init];
if (self) {
// 使用setValuesForKeys要求类的属性必须在字典中存在,可以比字典中的键值多,但是不能少。
[self setValuesForKeysWithDictionary:dict];
}
return self;
}