KVO 即 Key-Value Observing,翻译成键值观察。它是一种观察者模式的衍生。其基本思想是,对目标对象的某属性添加观察,当该属性发生变化时,通过触发观察者对象实现的KVO接口方法,来自动的通知观察者。
KVO和NSNotificationCenter都是iOS中观察者模式的一种实现。区别在于,相对于被观察者和观察者之间的关系,KVO是一对一的,而不一对多的。KVO对被监听对象无侵入性,不需要修改其内部代码即可实现监听。
使用KVO分为三个步骤:
-
通过addObserver:forKeyPath:options:context:方法注册观察者,观察者可以接收keyPath属性的变化事件。
-
在观察者中实现observeValueForKeyPath:ofObject:change:context:方法,当keyPath属性发生改变后,KVO会回调这个方法来通知观察者。
-
当观察者不需要监听时,可以调用removeObserver:forKeyPath:方法将KVO移除。需要注意的是,调用removeObserver需要在观察者消失之前,否则会导致Crash。
1. addObserver参数
※ options
addObserver:forKeyPath:options:context:
这个方法有个option,这个option有哪些呢?
NSKeyValueObservingOptionNew // 回调的时候提供新值
NSKeyValueObservingOptionOld // 回调的时候提供旧值
NSKeyValueObservingOptionInitial // 在注册观察服务时会调用一次触发方法,如果也选了new则change中会有新key,但即使加了old也不会有旧key
NSKeyValueObservingOptionPrior // 分别在值修改前后触发方法(即一次修改有两次触发),改之前触发的是绝对不会有新key的
具体属性的定义非常建议直接读苹果注释,然后也可以参考:https://www.jianshu.com/p/3bdc82e0ed4e
观察者的回调observeValueForKeyPath:ofObject:change:context:
传入的change参数里面会有NSKeyValueChangeNewKey/NSKeyValueChangeOldKey,这个就是根据option选了New还是Old还是都要决定的。
首先是下面所有尝试的base model类:
// .h文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface KVOTest : NSObject
@property (nonatomic, copy) NSString * name;
@end
NS_ASSUME_NONNULL_END
// .m文件
#import "KVOTest.h"
@interface KVOTest() {
NSString * name;
}
@end
@implementation KVOTest
- (void)setLastName:(NSString *)name {
self->name = name;
NSLog(@"name: %@", name);
}
@end
我们来尝试一下看看各种option的区别吧:
// 使用:
KVOTest *test1 = [[KVOTest alloc] init];
[test1 addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
test1.name = @"yy";
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"change:%@", change);
NSLog(@"context:%@", context);
}
首先是New的输出:
2019-12-11 08:14:21.247913+0800 Example1[68172:908391] change:{
kind = 1;
new = yy;
}
2019-12-11 08:14:21.248039+0800 Example1[68172:908391] context:(null)
然后Old是:
2019-12-11 08:14:51.049799+0800 Example1[68192:909085] change:{
kind = 1;
old = "<null>";
}
2019-12-11 08:14:51.050430+0800 Example1[68192:909085] context:(null)
然后initial是:
2019-12-11 08:15:23.586375+0800 Example1[68297:910116] change:{
kind = 1;
}
2019-12-11 08:15:23.586489+0800 Example1[68297:910116] context:(null)
2019-12-11 08:15:23.586789+0800 Example1[68297:910116] change:{
kind = 1;
}
2019-12-11 08:15:23.586872+0800 Example1[68297:910116] context:(null)
// 注释掉test1.name=@"yy"的输出:
2019-12-11 08:16:20.799515+0800 Example1[68328:911116] change:{
kind = 1;
}
2019-12-11 08:16:20.799639+0800 Example1[68328:911116] context:(null)
可以看到只要addObserver,initial类型就会有一次通知。
下面是prior啦:
2019-12-11 08:18:42.052983+0800 Example1[68372:913075] change:{
kind = 1;
notificationIsPrior = 1;
}
2019-12-11 08:18:42.053112+0800 Example1[68372:913075] context:(null)
2019-12-11 08:18:42.053251+0800 Example1[68372:913075] change:{
kind = 1;
}
2019-12-11 08:18:42.053333+0800 Example1[68372:913075] context:(null)
// 注释掉test1.name=@"yy"的输出:啥也木有输出
所以其实prior在改变前后都会有输出的~
当我们把四个属性都加上的时候的输出嘞:
// initial option触发的,只可能有new key,因为初始name未被赋值所以是null
2019-12-11 08:21:17.953893+0800 Example1[68392:914630] change:{
kind = 1;
new = "<null>";
}
2019-12-11 08:21:17.954026+0800 Example1[68392:914630] context:(null)
// before prior 时机触发的,不会有new key只有old key
2019-12-11 08:21:17.954325+0800 Example1[68392:914630] change:{
kind = 1;
notificationIsPrior = 1;
old = "<null>";
}
2019-12-11 08:21:17.954410+0800 Example1[68392:914630] context:(null)
// after prior时机触发的,也是正常如果只有New / Old时候的时机,会有new和old key,注意这里就木有before prior的notificationIsPrior啦
2019-12-11 08:21:17.954521+0800 Example1[68392:914630] change:{
kind = 1;
new = yy;
old = "<null>";
}
2019-12-11 08:21:17.954602+0800 Example1[68392:914630] context:(null)
※ kind
NSKeyValueChangeKindKey:这是change中永远会包含的键值对,它的值时一个NSNumber对象,具体的数值有:
typedef NS_ENUM(NSUInteger, NSKeyValueChange) {
NSKeyValueChangeSetting = 1,
NSKeyValueChangeInsertion = 2,
NSKeyValueChangeRemoval = 3,
NSKeyValueChangeReplacement = 4,
};
一般情况下返回的都是1也就是第一个NSKeyValueChangeSetting,但是如果你监听的属性是一个集合对象的话,当这个集合中的元素被插入,删除,替换时,就会分别返回NSKeyValueChangeInsertion,NSKeyValueChangeRemoval和NSKeyValueChangeReplacement。
我们来看下如何监听array增删改查,对应kind不是1的情况~
@property (nonatomic, copy) NSMutableArray *arr;
self.arr = [NSMutableArray array];
[self addObserver:self forKeyPath:NSStringFromSelector(@selector(arr)) options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
NSMutableArray *array = [self mutableArrayValueForKey:NSStringFromSelector(@selector(arr))];
[array addObject:@"ss"];
输出:
2019-12-15 20:20:20.968834+0800 Example1[23217:599988] change:{
indexes = "<_NSCachedIndexSet: 0x600001250720>[number of indexes: 1 (in 1 ranges), indexes: (0)]";
kind = 2;
new = (
ss
);
}
注意哦,只有用mutableArrayValueForKey
获取的自己的array属性才会触发KVO哦,因为如果你直接用self.arr来做增删改查其实并没有改arr这个属性值,是不会触发KVO的。
现在是每add一次都会触发一次KVO,如果要是想要一次加很多object,但是只触发一次KVO,可以试一下insertObjects: atIndexes:
。
※ context
下面这段其实我一直木有懂,我的感觉context还是用于区分到底这个KVO是谁加的监听,在防止crash方面木有感觉比不加强...如果有朋友有用context可以防止crash加了以后就不崩的例子欢迎私信。
KVO的一种缺陷(其实不能称为缺陷,应该称为特性)是,当对同一个 keypath进行两次removeObserver时会导致程序crash,父类在dealloc中remove 了一次,子类又remove了一次。
by the way,父类的dealloc方法会在子类dealloc方法返回后自动执行哦~
这个时候就需要KVO移除监听时,只移除自己的KVO,方法就是添加监听时设置不同的context,移除时移除对应的context。
这部分其实和之前看AFN的时候也有提及:https://www.jianshu.com/p/52bce82ded7b。
context其实就是用于区分子类父类到底是谁添加的,谁要处理这个observer。
比较对称的是自己加的就自己移除,如果子类父类监听了同一个keyPath,只能用context来区分是不是自己添加的observer啦,例如:
static int const PrivateKVOContext;
[otherObject addObserver:self forKeyPath:@"someKey" options:someOptions context:PrivateKVOContext];
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (context == PrivateKVOContext) {
// 这里写相关的观察代码
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
2. crash防护
可参考:http://www.cocoachina.com/cms/wap.php?action=article&id=34770
KVO 日常使用造成崩溃的原因通常有以下几个:
- KVO 添加次数和移除次数不匹配:
移除了未注册的观察者,导致崩溃。
重复移除多次,移除次数多于添加次数,导致崩溃。
重复添加多次,虽然不会崩溃,但是发生改变时,也同时会被观察多次。 - 被观察者提前被释放,被观察者在 dealloc 时仍然注册着 KVO,导致崩溃。 例如:被观察者是局部变量的情况(iOS 10 及之前会崩溃)。
- 添加了观察者,但未实现 observeValueForKeyPath:ofObject:change:context: 方法,导致崩溃。
- 添加或者移除时 keypath == nil,导致崩溃。
所以FB的KVOController就好用很多,通过内部维护了添加观察的key以及观察者dict,确保不重复添加observer,同时hook了dealloc方法,让观察者dealloc的时候自动移除observer。
3. 实现原理
假设我们有一个类是MJPerson,然后我们创建一个对象,给它加KVO监听。那么KVO会在运行时动态创建一个新类NSKVONotifying_MJPerson,让当前对象的isa指针指向新的类。NSKVONotifying_MJPerson的父类会指向MJPerson。
KVO原理此时当我们调用对象的setAge的时候,就会调用NSKVONotifying_MJPerson的setAge方法,setAge里面大概是酱紫的:
[self willChangeValueForKey:@"age"];
// 调用MJPerson的setAge
[super setAge:age];
[self didChangeValueForKey:@"age"];
- willChangeValueForKey和didChangeValueForKey是神马呢?
willChangeValueForKey的时候age的值就是old的值,也就是我们接到通知change里面的旧值;didChangeValueForKey的值是new值,也在通知change里。
正常如果你的option是new&old,那么会在didChangeValueForKey的时候回调你的observeValueForKeyPath,如果option是prior(改变前后都发通知),那么willChangeValueForKey的时候就会回调一次,然后调用super的setter,didChangeValueForKey再回调一次。
注意如果你只写了willChangeValueForKey,或者只写了didChangeValueForKey都是不会造成crash的,但是只写willChangeValueForKey我试了一下是是会回调observeValueForKeyPath的,但只写did好像是不会的。
- 父类子类KVO
如果在父类里面加了KVO,子类木有加那么运行时自动生成的类是啥嘞?
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Parent : NSObject
@property (nonatomic, strong) NSNumber * num;
@property (nonatomic, strong) NSNumber * num1;
@end
NS_ASSUME_NONNULL_END
===
@implementation Parent
- (instancetype)init {
if (self = [super init]) {
[self addObserver:self forKeyPath:NSStringFromSelector(@selector(num)) options:NSKeyValueObservingOptionNew context:@"hh"];
self.num = @10;
}
return self;
}
-(void)setNum:(NSNumber *)num {
NSLog(@"Parent set num");
_num = num;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"Parent observeValueForKeyPath");
NSLog(@"change:%@", change);
NSLog(@"class: %@, object_getClassName: %s", [self class], object_getClassName(self));
NSLog(@"super class: %@, object_getClassName super: %s", [self.superclass class], object_getClassName(self.superclass));
}
- (void)dealloc {
[self removeObserver:self forKeyPath:NSStringFromSelector(@selector(num)) context:@"hh"];
NSLog(@"parent dealloc");
}
@end
===
#import <Foundation/Foundation.h>
#import "Parent.h"
NS_ASSUME_NONNULL_BEGIN
@interface Child : Parent
@property (nonatomic) NSInteger hh;
@end
NS_ASSUME_NONNULL_END
===
@implementation Child
//@synthesize num = _num;
- (instancetype)init {
if (self = [super init]) {
// [self addObserver:self forKeyPath:NSStringFromSelector(@selector(num)) options:NSKeyValueObservingOptionPrior | NSKeyValueObservingOptionOld context:@"hhh"];
// self.num = @(20);
}
return self;
}
//-(void)setNum:(NSNumber *)num {
// NSLog(@"Child set num");
// _num = num;
//}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"Child observeValueForKeyPath");
NSLog(@"change:%@", change);
NSLog(@"class: %@, object_getClassName: %s", [self class], object_getClassName(self));
NSLog(@"super class: %@, object_getClassName super: %s", [self.superclass class], object_getClassName(self.superclass));
}
- (void)dealloc {
// [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(num)) context:@"hhh"];
NSLog(@"child dealloc");
}
@end
上面这段运行的结果是:
2019-12-17 08:29:06.914380+0800 Example1[28678:414836] Parent set num
2019-12-17 08:29:06.914522+0800 Example1[28678:414836] Child observeValueForKeyPath
2019-12-17 08:29:06.914692+0800 Example1[28678:414836] change:{
kind = 1;
new = 10;
}
2019-12-17 08:29:06.914794+0800 Example1[28678:414836] class: Child, object_getClassName: NSKVONotifying_Child
2019-12-17 08:29:06.914918+0800 Example1[28678:414836] super class: Parent, object_getClassName super: Parent
2019-12-17 08:29:06.915025+0800 Example1[28678:414836] child dealloc
2019-12-17 08:29:06.915125+0800 Example1[28678:414836] parent dealloc
虽然我们的KVO加到了Parent上面,但是运行时的self还是child,所以生成的是NSKVONotifying_Child,而且KVO生成新类还会把class方法hook一下返回child,隐藏起NSKVONotifying_Child,而且superclass也是Parent,而非NSKVONotifying_Child真正的super class(Child)。
如果注释掉child的observeValueForKeyPath,就会回调到parent的observeValueForKeyPath,这个是因为消息转发找不到就会去找父类哈,如果我们把observer加到子类上,子类不实现observeValueForKeyPath结果:
// Child.m
- (instancetype)init {
if (self = [super init]) {
[self addObserver:self forKeyPath:NSStringFromSelector(@selector(num)) options:NSKeyValueObservingOptionPrior | NSKeyValueObservingOptionOld context:@"hhh"];
self.num = @(20);
}
return self;
}
- (void)dealloc {
[self removeObserver:self forKeyPath:NSStringFromSelector(@selector(num)) context:@"hhh"];
NSLog(@"child dealloc");
}
@end
// Parent实现了:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"Parent observeValueForKeyPath");
NSLog(@"change:%@", change);
NSLog(@"class: %@, object_getClassName: %s", [self class], object_getClassName(self));
NSLog(@"super class: %@, object_getClassName super: %s", [self.superclass class], object_getClassName(self.superclass));
}
然后输出是:
2019-12-17 08:42:11.197897+0800 Example1[28769:422379] Parent observeValueForKeyPath
2019-12-17 08:42:11.198102+0800 Example1[28769:422379] change:{
kind = 1;
notificationIsPrior = 1;
old = "<null>";
}
2019-12-17 08:42:11.198189+0800 Example1[28769:422379] class: Child, object_getClassName: NSKVONotifying_Child
2019-12-17 08:42:11.198264+0800 Example1[28769:422379] super class: Parent, object_getClassName super: Parent
2019-12-17 08:42:11.198326+0800 Example1[28769:422379] Parent set num
2019-12-17 08:42:11.198393+0800 Example1[28769:422379] Parent observeValueForKeyPath
2019-12-17 08:42:11.198493+0800 Example1[28769:422379] change:{
kind = 1;
old = "<null>";
}
2019-12-17 08:42:11.198558+0800 Example1[28769:422379] class: Child, object_getClassName: NSKVONotifying_Child
2019-12-17 08:42:11.198618+0800 Example1[28769:422379] super class: Parent, object_getClassName super: Parent
2019-12-17 08:42:11.198852+0800 Example1[28769:422379] child dealloc
2019-12-17 08:42:11.199104+0800 Example1[28769:422379] parent dealloc
因为加了prior类型所以改变前后都会发通知,可以看到虽然子类加了observer,而且没实现observe方法,但是回调会走parent的observeValueForKeyPath。如果子类父类都没实现observeValueForKeyPath是会crash的哦!(是在value改变触发回调的时候crash,不是注册addObserver的时候)
通过runtime拿到method list可以看到child有给个_isKVOA
方法,_isKVOA
标记了是不是notifying类。
NSLog(@"object method list \n");
unsigned int count;
Method *methodList = class_copyMethodList(objectRuntimeClass, &count);
for (NSInteger i = 0; i < count; i++) {
Method method = methodList[i];
NSString *methodName = NSStringFromSelector(method_getName(method));
NSLog(@"method Name = %@\n", methodName);
}
输出:
2019-12-17 22:14:24.966008+0800 Example1[39130:375730] object method list
2019-12-17 22:14:24.966336+0800 Example1[39130:375730] method Name = setNum:
2019-12-17 22:14:24.966550+0800 Example1[39130:375730] method Name = class
2019-12-17 22:14:24.966834+0800 Example1[39130:375730] method Name = dealloc
2019-12-17 22:14:24.967110+0800 Example1[39130:375730] method Name = _isKVOA
有木有发现有个setNum方法,其实notifying这个类只有你add监听的key的setter方法,以及基础的isKVOA&class方法之类的,其他的方法调用的时候直接转发给父类了。
试一下下面的代码:
Child *child = [[Child alloc] init];
NSLog(@"child des1 %@==============", child);
[child addObserver:self forKeyPath:@"hh" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
NSLog(@"child des2 %@==============", child);
[child addObserver:self forKeyPath:@"num" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
NSLog(@"child des3 %@==============", child);
并且重写Child的description方法:
- (NSString *)description {
Class objectRuntimeClass = object_getClass(self);
NSLog(@"object method list \n");
unsigned int count;
Method *methodList = class_copyMethodList(objectRuntimeClass, &count);
for (NSInteger i = 0; i < count; i++) {
Method method = methodList[i];
NSString *methodName = NSStringFromSelector(method_getName(method));
NSLog(@"method Name = %@\n", methodName);
}
return @"";
}
输出:
2019-12-17 23:01:38.766174+0800 Example1[39431:398744] object method list
2019-12-17 23:01:38.766352+0800 Example1[39431:398744] method Name = hh
2019-12-17 23:01:38.766436+0800 Example1[39431:398744] method Name = setHh:
2019-12-17 23:01:38.766524+0800 Example1[39431:398744] method Name = init
2019-12-17 23:01:38.766599+0800 Example1[39431:398744] method Name = description
2019-12-17 23:01:38.766675+0800 Example1[39431:398744] method Name = dealloc
2019-12-17 23:01:38.766752+0800 Example1[39431:398744] method Name = observeValueForKeyPath:ofObject:change:context:
2019-12-17 23:01:38.766827+0800 Example1[39431:398744] child des1 ==============
2019-12-17 23:01:38.767090+0800 Example1[39431:398744] object method list
2019-12-17 23:01:38.767173+0800 Example1[39431:398744] method Name = setHh:
2019-12-17 23:01:38.767250+0800 Example1[39431:398744] method Name = class
2019-12-17 23:01:38.767337+0800 Example1[39431:398744] method Name = dealloc
2019-12-17 23:01:38.767508+0800 Example1[39431:398744] method Name = _isKVOA
2019-12-17 23:01:38.767690+0800 Example1[39431:398744] child des2 ==============
2019-12-17 23:01:38.792710+0800 Example1[39431:398744] object method list
2019-12-17 23:01:38.792813+0800 Example1[39431:398744] method Name = setNum:
2019-12-17 23:01:38.792903+0800 Example1[39431:398744] method Name = setHh:
2019-12-17 23:01:38.793002+0800 Example1[39431:398744] method Name = class
2019-12-17 23:01:38.793104+0800 Example1[39431:398744] method Name = dealloc
2019-12-17 23:01:38.793176+0800 Example1[39431:398744] method Name = _isKVOA
2019-12-17 23:01:38.793257+0800 Example1[39431:398744] child des3 ==============
可以看到最开始的child方法还是正常的,但是add过一次属性hh的observer以后,方法列表就消失了很多,只剩下setHh
和_isKVOA
,然后又add了一次num属性的observer以后,多了一个setNum
方法。
4. 手动KVO
如果想自己手动控制是不是要发通知,那么重载一下类方法即可:
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
return NO;
}
注意哦,如果你的automaticallyNotifiesObserversForKey永远返回NO,那么其实苹果没有必要给你建一个新的notifying类了,因为你自己就会管理发送通知了,所以这种时候不会在运行时偷偷建一个notifying。
你可以通过debug打一个断点,po object_getClassName(self)
看一下当前类到底是神马~
手动的话就和上面的原理是一致的,就是自己在setter里面调用willChangeValueForKey和didChangeValueForKey就可以了。
- (void)setNum:(NSNumber *)num {
[self willChangeValueForKey:@"num"];
_num = num;
[self didChangeValueForKey:@"num"];
}
注意哦,其实willChangeValueForKey和didChangeValueForKey里面的key你可以随便写,底层并没有校验这个key是不是存在,如果你把上面改成[self willChangeValueForKey:@"numm"];
并不会crash的,addObserver的时候如果key木有也不会crash的。
如果一个属性age的改变会影响另外一个属性例如身高height,你可以在setter里面:
- (void)setAge:(NSNumber *)age {
[self willChangeValueForKey:@"age"];
[self willChangeValueForKey:@"height"];
_age = age;
_height = @([age intValue] * 10);
[self didChangeValueForKey:@"age"];
[self didChangeValueForKey:@"height"];
}
那么KVC 修改属性会触发KVO么?
会触发KVO的,因为KVC内部会实现willChangeValueForKey:以及didChangeValueForKey:
@interface Parent() {
NSString *name;
}
@end
@implementation Parent
- (instancetype)init {
if (self = [super init]) {
[self addObserver:self forKeyPath:NSStringFromSelector(@selector(name)) options:NSKeyValueObservingOptionPrior context:@"hh"];
[self setValue:@"yingying" forKey:@"name"];
}
return self;
}
以上代码还是会触发observeValueForKeyPath的哦,所以其实没有setter方法的实例变量,如果用KVC改也会触发KVO,不是只有属性的set方法才会哦。
像上面那种一个值得改变可能影响其他几个值的状况,也可以用keyPathsForValuesAffectingXXX
或者keyPathsForValuesAffectingValueForKey
。
假设有两个属性num1和num,如果想在num改变的时候也通知num1的监听者,就可以设置num是affect num1的~
+ (NSSet<NSString *> *)keyPathsForValuesAffectingNum1 {
return [NSSet setWithArray:@[@"num"]];
}
+ (NSSet<NSString *> *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
NSSet * keyPaths = [super keyPathsForValuesAffectingValueForKey:key];
NSArray * moreKeyPaths = nil;
if ([key isEqualToString:@"num1"]) {
moreKeyPaths = [NSArray arrayWithObjects:@"num", nil];
}
if (moreKeyPaths) {
keyPaths = [keyPaths setByAddingObjectsFromArray:moreKeyPaths];
}
return keyPaths;
}
如果选择实现 keyPathsForValuesAffectingValueForKey,要先获取super 返回的结果set,然后看是不是要追加哦~
5. tips
利用 KVO,关注对象某属性的变化,当该属性变化时,处理该属性变化的观察者处理方法被调用:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
需要注意的是该处理方法,被调用时所在的线程,位于被观察的属性变化时的线程里。
比如,在线程3里改变了对象属性,那么,该处理方法就在线程3里被调用。因此,若在该处理方法里有更新UI的操作时,需要在该方法里,切入主线程再操作。
KVOTest *test1 = [[KVOTest alloc] init];
[test1 addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
test1.name = @"yy";
NSLog(@"thread set name: %@", [NSThread currentThread]);
});
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"change:%@", change);
NSLog(@"thread observer:%@", [NSThread currentThread]);
}
输出:
2019-12-17 23:08:28.870885+0800 Example1[39491:403260] change:{
kind = 1;
new = yy;
}
2019-12-17 23:08:28.871052+0800 Example1[39491:403260] thread observer:<NSThread: 0x600001b3bb80>{number = 5, name = (null)}
2019-12-17 23:08:28.871162+0800 Example1[39491:403260] thread set name: <NSThread: 0x600001b3bb80>{number = 5, name = (null)}
可以看出来一个是confirm了之前其实willchange和didchange里面回调了observeValueForKeyPath ,所以test1.name = @"yy";
执行的时候就回调了observeValueForKeyPath,然后再打印了@"thread set name: %@"
,并且改变name的thread和observeValueForKeyPath回调的thread是一致的。
大概是在willchange和didchange里直接执行的observeValueForKeyPath,所以observeValueForKeyPath线程和willchange等是一样的,那么也就和setter线程一致了。
为了看着方便我木有都用下面的写,但是推荐项目里都不要直接用string哦,最好用selector转string:
NSStringFromSelector(@selector(XXX))
finally,感冒了一周多了终于好了起来,感谢北京这场大雪带走了我久违的头疼眼睛疼鼻子疼智商疼。。
参考:
https://www.jianshu.com/p/91c41292b5b9
https://www.jianshu.com/p/d104daf7a062
https://www.jianshu.com/p/badf5cac0130
https://www.jianshu.com/p/1f7d70ff2002
https://www.jianshu.com/p/4eae365accc1
https://www.jianshu.com/p/b9f020a8b4c9
https://blog.csdn.net/caryaliu/article/details/49284185
https://www.jianshu.com/p/f98c4627e1d1
https://blog.csdn.net/yawei147/article/details/49668227
网友评论