KVO原理理解2018-07-18

2018-07-18  本文已影响10人  iOS打怪升级
  1. 如何自己动手实现 KVO
    cocoachina 上的一篇,有点乱

需要注意的方法:这里会才坑 :

/*
* @param  cls :当前需要修改的类
* @param name  被添加的方法的名字
* @param imp    被添加方法的实现函数指针
* @param types  表示方法参数类型列表的一个数组字符: 其中因为方法最少两个参数self 和_cmd ,所以第二个和第三个参数一定是@:    ,types里面的第一个字符表示返回值类型。

*/
class_addMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, 
                const char * _Nullable types) ;

types 详细规则可以参考官方文档

types 举例:
方法是 - (void)setName:(NSString *)name
IMP :static void KVO_setterMethod(id self, SEL _cmd, id newValue){}
types: v@:@

方法是 - (void)setAge:(int)age
IMP:IMP :static void KVO_setterMethod(id self, SEL _cmd,int newValue){}
types: v@:i

自己写了一遍DEMO:

  1. 关于常用的方法交叉使用
1. 字符串获取SEL  : NSSelectorFromString

   SEL setterSeL = NSSelectorFromString("methodName");


2. SEL 获取Method : class_getInstanceMethod

   Method setterMethod = class_getInstanceMethod(self.class, setterSeL);

3. Method 获取IMP : method_getImplementation

   IMP methodIMP =  method_getImplementation(setterMethod)


总结:name > SEL > Method > IMP

  1. runtime 方法报错
//报错 Too many arguments to function call ,expected 0,have3
 objc_msgSend(self, @selector(setAge:),age); 

原因:默认编译器对objc_msgSend 是严格检查的,可以手动设置是否启动严格检查

解决办法:Build Setting--> Apple LLVM 6.0 - Preprocessing--> Enable Strict Checking of objc_msgSend Calls  改为 NO

  1. 官方Runtime 编程指导
上一篇 下一篇

猜你喜欢

热点阅读