iOS-KVC模式

来源:互联网 发布:经济和信息化数据平台 编辑:程序博客网 时间:2024/05/21 08:44
全称是Key-value coding,翻译成键值编码。顾名思义,在某种程度上跟map的关系匪浅。它提供了一种使用字符串而不是访问器方法去访问一个对象实例变量的机制。在iOS中定义模型一般使用如下带啊创建模型
#import "HMQuestion.h"@implementation HMQuestion-(instancetype)initWithDict:(NSDictionary *)dict{    self = [super init];    if (self) {        //用KVC直接赋值plist所有的属性        [self setValuesForKeysWithDictionary:dict];    }    return self;}+(instancetype)questionWithDict:(NSDictionary *)dict{    return [[self alloc] initWithDict:dict];}+(NSArray *)questions{    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];    NSMutableArray *arrayM = [NSMutableArray array];    for (NSDictionary *dict in array) {        [arrayM addObject:[self questionWithDict:dict]];    }    return arrayM;}//对象描述方法,便于跟踪调试、建议:如果是自定义的模型,最好编写description方法-(NSString *)description{    return [NSString stringWithFormat:@"<%@: %p> {answer:%@, icon:%@, title:%@, options:%@}",self.class,self,self.answer,self.icon,self.title,self.options];}@end

用KVC 省去了对模型中单个变量逐一赋值,仅用一个语句即可实现所有属性的赋值,勘称Cocoa的大招

KVC 也可以直接通过字符串赋值,
// 用来间接获取或者修改对象属性的方式
// 使用KVC在获取数值时,如果指定对象不包含keyPath的”键名”,会自动进入对象的内部查找
// 如果取值的对象是一个数组,同样返回一个数组

0 0