iOS KVO机制

   来自官方文档的使用步骤

step

  • 调用addObserver:forKeyPath:options:context: 方法来注册观察者
  • 在观察者内实现observeValueForKeyPath:ofObject:change:context:可以接收到属性发生变化的通知
  • 当观察者不再需要接收消息时,需要调用removeObserver:forKeyPath:移除监听,至少应在观察者释放之前调用。
我们先看一下自动触发KVO

创一个Human类,加上name,age属性,并监听,实现observeValueForKeyPath:ofObject:change:context ,修改一下值.

self.human.name = @"lili";
self.human.age = 19;
[self.human addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
[self.human addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.human.name = [self.human.name isEqual:@"lili"]?@"lala":@"lili";
    self.human.age = self.human.age==19?20:19;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"name"]) {
        NSLog(@"observeValueForKeyPath -- %@ -- %@ -- %@",keyPath,object,self.human.name);
    }else if ([keyPath isEqualToString:@"age"]){
        NSLog(@"observeValueForKeyPath -- %@ -- %@ -- %ld",keyPath,object,self.human.age);
    }
}

可以看到打印结果

observeValueForKeyPath -- name -- <Human: 0x600001462ce0> -- lala
observeValueForKeyPath -- age -- <Human: 0x600001462ce0> -- 20

手动触发KVO

首先在automaticallyNotifiesObserversForKey禁掉name的触发

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {
    if ([theKey isEqualToString:@"name"]) {
        return NO;
    }
    return [super automaticallyNotifiesObserversForKey:theKey];
}

这里就需要用到下面2个方法了

willChangeValueForKey:
didChangeValueForKey:

-(void)updateName:(NSString *)name{
   // _name = name;
    [self willChangeValueForKey:@"name"];
    _name = name;
    [self didChangeValueForKey:@"name"];
}

当我调用[self.human updateName:@"lala"]; ,一样的会收到name变化的通知

observeValueForKeyPath -- name -- <Human: 0x600002bef5a0> -- lala

那么KVC是怎么实现的呢,苹果的文档这么说的

kvo

意思是KVO是基于isa-swizzling实现的,在注册观察者的时候,会修改观察对象的isa指向。不要使用isa指针来判断类的关系,而应该使用class方法。

接下来我们就基于这个来从代码看看KVO的实现。
NSLog(@"object_getClass -- %@ --%@",object_getClass(self.human),[self.human class]);
    NSLog(@"address -- %p -- %p",object_getClass(self.human),[self.human class]);
    NSLog(@"%@",[self getMethods:object_getClass(self.human)]);
    [self.human addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    [self.human addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    NSLog(@"addObserver ----------------");
    NSLog(@"object_getClass -- %@ --%@",object_getClass(self.human),[self.human class]);
    NSLog(@"address -- %p -- %p",object_getClass(self.human),[self.human class]);
    NSLog(@"%@",[self getMethods:object_getClass(self.human)]);
    
    [self.human removeObserver:self forKeyPath:@"name"];
    [self.human removeObserver:self forKeyPath:@"age"];
    NSLog(@"removeObserver ----------------");
    NSLog(@"object_getClass -- %@ --%@",object_getClass(self.human),[self.human class]);
    NSLog(@"address -- %p -- %p",object_getClass(self.human),[self.human class]);
    NSLog(@"%@",[self getMethods:object_getClass(self.human)]);
/// 获取class的方法
-(NSArray *)getMethods:(Class)cls{
    NSMutableArray *array = [NSMutableArray array];
    unsigned int methodCount = 0;
    Method * methodList = class_copyMethodList(cls, &methodCount);
    unsigned int i;
    for(i = 0; i < methodCount; i++) {
        [array addObject:NSStringFromSelector(method_getName(methodList[i]))];
    }
    free(methodList);
    return array;
}

可以看到打印结果如下

[5779:346617] object_getClass -- Human --Human
[5779:346617] address -- 0x103de0818 -- 0x103de0818
[5779:346617] (
"updateName:",
name,
".cxx_destruct",
"setName:",
"setAge:",
age
)
[5779:346617] addObserver ----------------
[5779:346617] object_getClass -- NSKVONotifying_Human --Human
[5779:346617] address -- 0x6000015b4480 -- 0x103de0818
[5779:346617] (
"setName:",
"setAge:",
class,
dealloc,
"_isKVOA"
)
[5779:346617] removeObserver ----------------
[5779:346617] object_getClass -- Human --Human
[5779:346617] address -- 0x103de0818 -- 0x103de0818
[5779:346617] (
"updateName:",
name,
".cxx_destruct",
"setName:",
"setAge:",
age
)

如文档所说 isa确实发生了变化Human(0x103de0818)-> NSKVONotifying_Human(0x6000015b4480)-> Human(0x103de0818),
可以看出在addObserver ,会将self.humanisa指向NSKVONotifying_Human, 根据打印结果我们可以看到NSKVONotifying_Human"setAge:","setName:",class,dealloc,"_isKVOA"这些方法。

那么可能就会想到一个问题,添加监听之后,isa已经改变,而NSKVONotifying_Human里面却没有了updateName等其他方法,这时候调用不会出错吗?

但是实际情况是不会出错的。
我们来打印一下NSKVONotifying_Human的父类

NSLog(@"-- super %@",class_getSuperclass(object_getClass(self.human)));

[5921:361806] -- super Human

好家伙,竟然是Human。那么这样就没问题了,可以去父类找到方法实现了。

所以这里明白了NSKVONotifying_Human继承了Human ,并重写/增加了些方法。
  • 重写set方法,来支持KVO
  • 重写class方法,假装自己还是Human类(这里就说明了打印[self.human class]按道理应该是打印isa指向NSKVONotifying_Human,而实际是一直都没有变化,还是Human
  • 重写dealloc方法,做一些实例销毁时的清理工作
  • 添加了_isKVOA方法,来说明自己是kvo类
接下来重写一下willChangeValueForKeydidChangeValueForKey,来看看给出通知的时机。
-(void)willChangeValueForKey:(NSString *)key{
    [super willChangeValueForKey:key];
    NSLog(@"willChangeValueForKey");
}
-(void)didChangeValueForKey:(NSString *)key{
    NSLog(@"didChangeValueForKey - 111111");
    [super didChangeValueForKey:key];
    NSLog(@"didChangeValueForKey - 222222");
}

observeValueForKeyPath打上断点

kvo

[6337:400843] willChangeValueForKey
[6337:400843] didChangeValueForKey - 111111
[6337:400843] observeValueForKeyPath -- name -- <Human: 0x600003c48900> -- lala
[6337:400843] didChangeValueForKey - 222222

可以看出didChangeValueForKey内会给出通知

以上就是对KVO的一些分析

end

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354