分类: 大数据
2022-11-29 10:39:57
作者:宋宏帅
在技术论坛中看到一则很有意思的kvc案例:
interface person : nsobject @property (nonatomic, copy) nsstring *name; @property (nonatomic, assign) nsinteger age; @end person *person = [person new];
person.name = @"tom";
person.age = 10;
[person setvalue:@"100" forkey:@"age"];//此处赋值为字符串,类中属性为integer
{banned}中国第一反应是崩溃,因为oc是类型敏感的。可是自己实现并打印后的结果出于意料,没有崩溃且赋值成功。所以有了深入了解kvc的内部实现的想法!
key-value-coding:键值编码,一种可以通过键名间接访问和赋值对象属性的机制kvc是通过nsobject、nsarray、nsdictionary等的类别来实现的主要方法包括一下几个:
- (nullable id)valueforkey:(nsstring *)key;
- (void)setvalue:(nullable id)value forkey:(nsstring *)key;
- (void)setnilvalueforkey:(nsstring *)key;
- (void)setvalue:(nullable id)value forundefinedkey:(nsstring *)key;
- (nullable id)valueforundefinedkey:(nsstring *)key;
那么上面的案例中的- (void)setvalue:(nullable id)value forkey:(nsstring *)key;是怎样的执行过程呢?借助反汇编工具获得foundation.framework部分源码(为了解决和系统api冲突问题增加前缀_d,ns替换为ds),以此分析kvc执行过程。(流程中的边界判断等已经忽略,如想了解可以参考源码,本文只探究主流程。)
(dskeyvaluesetter *)_d_createvaluesetterwithcontainerclassid:(id)containerclassid key:(nsstring *)key {
dskeyvaluesetter *setter = nil; char key_cstr_upfirst[key_cstr_len 1];
key_cstr[key_cstr_len 1]; ... method method = null; //按顺序寻找set,_set,setis。找到后则生成对应的seter if ((method = dskeyvaluemethodforpattern(self, "set%s:", key_cstr_upfirst)) || (method = dskeyvaluemethodforpattern(self, "_set%s:", key_cstr_upfirst)) || (method = dskeyvaluemethodforpattern(self, "setis%s:", key_cstr_upfirst))
) { //生成method:包含selector,imp。返回和参数类型字符串 setter = [[dskeyvaluemethodsetter alloc] initwithcontainerclassid:containerclassid key:key method:method];
} else if ([self accessinstancevariablesdirectly]) {//如果没有找到对应的访问器方且工厂方法accessinstancevariablesdirectly == ture ,则按照顺序查找查找成员变量_,_is,,is(注意key的首字母大小写,查找到则生成对应的setter) ivar ivar = null; if ((ivar = dskeyvalueivarforpattern(self, "_%s", key_cstr)) || (ivar = dskeyvalueivarforpattern(self, "_is%s", key_cstr_upfirst)) || (ivar = dskeyvalueivarforpattern(self, "%s", key_cstr)) || (ivar = dskeyvalueivarforpattern(self, "is%s", key_cstr_upfirst))
) {
setter = [[dskeyvalueivarsetter alloc] initwithcontainerclassid:containerclassid key:key containerisa:self ivar:ivar];
}
} ... return setter;
}
查找顺序如下:
则查找顺序如下:_,_is,,is查找不到则调用valueforundefinedkey并抛出异常
3.1.2 生成setter (dskeyvaluesetter *)_d_createothervaluesetterwithcontainerclassid:(id)containerclassid key:(nsstring *)key { return [[dskeyvalueundefinedsetter alloc] initwithcontainerclassid:containerclassid key:key containerisa:self];
} //构造方法确定方法编号 d_setvalue:forundefinedkey: 和方法指针imp _dssetvalueandnotifyforundefinedkey - (id)initwithcontainerclassid:(id)containerclassid key:(nsstring *)key containerisa:(class)containerisa {
... return [super initwithcontainerclassid:containerclassid key:key implementation:method_getimplementation(class_getinstancemethod(containerisa, @selector(d_setvalue:forundefinedkey:))) selector:@selector(d_setvalue:forundefinedkey:) extraarguments:arguments count:1];
}
3.1.3 赋值
基本的访问器方法、变量的查找和异常处理已经清楚的知道了。那么上面的例子是如何出现的呢?明明传入的是字符串,{banned}最佳后赋值的时候转变为访问器方法所对应的类型?继续刨根问底!
dskeyvaluesetter对象已经生成,即确定了发送消息的对象object、访问器方法名sel、访问器函数指针imp、以及使用kvc时传入的key和value。下面进入方法调用阶段:_dssetusingkeyvaluesetter(self,setter, value);
imp指针为_dssetintvalueforkeywithmethod其定义如下:之所以有文章开头提到的效果就是这里起了作用,在imp调用的时候做了[value valuegetselectorname],将对应的nsnumber转换为简单数据类型。这里是intvalue。
void _dssetintvalueforkeywithmethod(id object, sel selector,id value, nsstring *key, method method) {// object:person selector:setage: value:@(100) key:age method:selector imp 返回类型和参数类型 即_extraargument2,其在{banned}中国第一步查找到访问器方法后生成 __dssetprimitivevalueforkeywithmethod(object, selector, value, key, method, int, intvalue);
}
#define __dssetprimitivevalueforkeywithmethod(object, selector, value, key, method, valuetype, valuegetselectorname) do {\ if (value) {\
void (*imp)(id,sel,valuetype) = (void (*)(id,sel,valuetype))method_getimplementation(method);\
imp(object, method_getname(method), [value valuegetselectorname]);\调用person的setage:方法。参数为100 }\ else {\ [object setnilvalueforkey:key];\
}\
}while(0) //如果{banned}中国第一步中没有找到访问器方法只找到了成员变量则直接执行赋值操作 void _dssetintvalueforkeyinivar(id object, sel selector, id value, nsstring *key, ivar ivar) { if (value) {
*(int *)object_getivaraddress(object, ivar) = [value intvalue];
} else { [object setnilvalueforkey:key];
}
}
起始问题完美解决!执行流程如下:
(dskeyvaluegetter *)_d_createvaluegetterwithcontainerclassid:(id)containerclassid key:(nsstring *)key {
dskeyvaluegetter * getter = nil; ... method getmethod = null; if((getmethod = dskeyvaluemethodforpattern(self,"get%s",keycstrupfirst)) || (getmethod = dskeyvaluemethodforpattern(self,"%s",keycstr)) || (getmethod = dskeyvaluemethodforpattern(self,"is%s",keycstrupfirst)) || (getmethod = dskeyvaluemethodforpattern(self,"_get%s",keycstrupfirst)) || (getmethod = dskeyvaluemethodforpattern(self,"_%s",keycstr))) {
getter = [[dskeyvaluemethodgetter alloc] initwithcontainerclassid:containerclassid key:key method:getmethod];
}// 查找对应的访问器方法 ... else if([self accessinstancevariablesdirectly]) {//查找属性 ivar ivar = null; if((ivar = dskeyvalueivarforpattern(self, "_%s", keycstr)) || (ivar = dskeyvalueivarforpattern(self, "_is%s", keycstrupfirst)) || (ivar = dskeyvalueivarforpattern(self, "%s", keycstr)) || (ivar = dskeyvalueivarforpattern(self, "is%s", keycstrupfirst))
) {
getter = [[dskeyvalueivargetter alloc] initwithcontainerclassid:containerclassid key:key containerisa:self ivar:ivar];
}
}
} if(!getter) {
getter = [self _d_createvalueprimitivegetterwithcontainerclassid:containerclassid key:key];
}
return getter;
}
访问器方法生成imp
- (id)initwithcontainerclassid:(id)containerclassid key:(nsstring *)key method:(method)method {
nsuinteger methodargumentscount = method_getnumberofarguments(method);
nsuinteger extraatgumentcount = 1;
if(methodargumentscount == 2) {
char *returntype = method_copyreturntype(method);
imp imp = null;
switch (returntype[0]) {
...
case 'i': {
imp = (imp)_dsgetintvaluewithmethod;
} break;
...
free(returntype); if(imp) {
void *arguments[3] = {0}; if(extraatgumentcount > 0) {
arguments[0] = method;
} return [super initwithcontainerclassid:containerclassid key:key implementation:imp selector:method_getname(method) extraarguments:arguments count:extraatgumentcount]; }
}
单步调试后可以看到具体的imp类型
定义如下:
nsnumber * _dsgetintvaluewithmethod(id object, sel selctor, method method) {// return [[[nsnumber alloc] initwithint: ((int (*)(id,sel))method_getimplementation(method))(object, method_getname(method))] autorelease];
}
3.2.3 取值
取值调用如下:
nsnunber:
nsvalue
修改数组中对象的属性[array valueforkeypath:@”uppercasestring”]利用kvc可以批量修改属性的成员变量值
求和,平均数,{banned}最佳大值,{banned}最佳小值nsnumbersum= .self”];nsnumberavg= .self”];nsnumbermax= .self”];nsnumbermin= .self”];
经过上面的分析可以明白kvc的真正执行流程。下面结合日常工程中的实际应用来优雅的处理数据筛选问题。使用kvc处理可以减少大量for的使用并增加代码可读性和健壮性。如图所示:
项目中的细节如下:修改拒收数量时更新总妥投数和总拒收数、勾选明细更新总妥投数和总拒收数、全选、清空、反选。如果用通常的做法是每次操作都要循环去计算总数和记录选择状态。下面是采用kvc的实现过程。模型涉及:
@property (nonatomic,copy)nsstring* skucode; @property (nonatomic,copy)nsstring* goodsname; @property (nonatomic,assign)nsinteger totalamount; @property (nonatomic,assign)nsinteger rejectamount; @property (nonatomic,assign)nsinteger deliveryamount; ///单选用 @property (nonatomic, assign) bool selected;
1)更新总数
- (void)updatedeliveryinfo { //总数 nsnumber *alldeliveryamount = [self.orderdetailmodel.deliverygoodsdetaillist valueforkeypath:@"@sum.totalamount"]; //妥投数 nsnumber *allrealdeliveryamount = [self.orderdetailmodel.deliverygoodsdetaillist valueforkeypath:@"@sum.deliveryamount"]; //拒收数 nsnumber *allrejectamount = [self.orderdetailmodel.deliverygoodsdetaillist valueforkeypath:@"@sum.rejectamount"];
}
2)全选[self.orderdetailmodel.deliverygoodsdetaillist setvalue:@(yes) forkeypath:@”selected”];
3)清空[self.orderdetailmodel.deliverygoodsdetaillist setvalue:@(no) forkeypath:@”selected”];
4)反选
nspredicate *selectedpredicate = [nspredicate predicatewithformat:@"selected == %@",@(yes)]; nsarray *selectedarray = [self.orderdetailmodel.deliverygoodsdetaillist filteredarrayusingpredicate:selectedpredicate]; nspredicate *unselectedpredicate = [nspredicate predicatewithformat:@"selected == %@",@(no)]; nsarray *unselectedarray = [self.orderdetailmodel.deliverygoodsdetaillist filteredarrayusingpredicate:unselectedpredicate];
[selectedarray setvalue:@(no) forkeypath:@"selected"];
[unselectedarray setvalue:@(yes) forkeypath:@"selected"];
kvc在处理简单数据类型时会经过数据封装和拆装并转换为对应的数据类型。通过kvc的特性我们可以在日常使用中更加优雅的对数据进行筛选和处理。优点如下:可阅读性更高,健壮性更好。