KVO
KVO的全称是Key-Value-Observing,俗称“键值监听”,可以用于监听某个对象属性的改变。
1、KVO的使用
- 注册Observer
- 接收属性值的改变
- 移除Observer
1.1、注册Observer
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
observer
观察者,监听属性变化的对象,该对象必须实现
keyPath
要观察的属性名称
options
调用接收方法的时机以及包含的内容
context
上下文,可以传入任意类型的对象,将在消息回调时,接收这个对象。
options 参数解读,一般我们使用NSKeyValueObservingOptionNew
和NSKeyValueObservingOptionOld
typedef NS_OPTIONS(NSUInteger, NSKeyValueObservingOptions) {
NSKeyValueObservingOptionNew = 0x01,
NSKeyValueObservingOptionOld = 0x02,
NSKeyValueObservingOptionInitial API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 0x04,
NSKeyValueObservingOptionPrior API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 0x08
};
NSKeyValueObservingOptionNew:接收方法的change参数的中包含新的值(NSKeyValueChangeNewKey)
NSKeyValueObservingOptionOld:接收方法的change参数的中包含旧的值(NSKeyValueChangeOldKey)
NSKeyValueObservingOptionInitial:注册的时候发一次通知,改变后也发送一次通知
NSKeyValueObservingOptionPrior:属性改变之前发一次,改变之后再发一次,变化前的通知change参数包含notificationIsPrior = 1
1.2、接收属性值的改变
- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context;
keyPath
被观察的属性名称
object
被观察的对象
change
在注册是用options
参数进行的配置,包含的内容
context
上下文
change的key(NSKeyValueChangeKey)有以下几种
NSKeyValueChangeSetting = 1, // 赋值(下面demo中打印结果就是kind==1)
NSKeyValueChangeInsertion = 2, // 插入
NSKeyValueChangeRemoval = 3, // 移除
NSKeyValueChangeReplacement = 4,// 替换
NSKeyValueChangeNewKey, // 新值
NSKeyValueChangeOldKey, // 旧值
1.3、移除Observer
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
observer
要移除的观察者
keyPath
要移除的属性名称
1.4、Demo
@interface Person : NSObject
@property (assign, nonatomic) int age;
@end
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property (strong, nonatomic) Person *person;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [[Person alloc] init];
self.person.age = 1;
// 1、给person对象添加KVO监听
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person addObserver:self forKeyPath:@"age" options:options context:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.person.age = 20;
}
- (void)dealloc {
// 3、移除Observer
[self.person removeObserver:self forKeyPath:@"age"];
}
// 2、当监听对象的属性值发生改变时,就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"监听到==%@==的==%@==属性值改变了 - %@ - %@", object, keyPath, change, context);
}
@end
打印
监听到==<Person: 0x600003eacd90>==的==age==属性值改变了 - {
kind = 1;
new = 20;
old = 1;
} - (null)
2、KVO 的本质
只贴出部分代码, 如下,我们只对person1
进行监听,看打印的结果
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[Person alloc] init];
self.person1.age = 1;
self.person2 = [[Person alloc] init];
self.person2.age = 2;
// 给person1对象添加KVO监听
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.person1.age = 11;
self.person2.age = 22;
}
打印结果看,值对person1
进行了打印,person2
却没有打印。
(lldb) po self.person1
<Person: 0x60000177bb30>
监听到==<Person: 0x60000177bb30>==的==age==属性值改变了 - {
kind = 1;
new = 11;
old = 1;
} - (null)
在改变age
的地方打断点,分别打印person1
和person2
调试剖析代码
(lldb) p self.person1.isa
(Class) $2 = NSKVONotifying_Person
Fix-it applied, fixed expression was:
self.person1->isa
(lldb) p self.person2.isa
(Class) $3 = Person
Fix-it applied, fixed expression was:
self.person2->isa
我们发现,两个isa
(实例对象isa指向类对象)不一样
person1
的isa指向的是NSKVONotifying_Person
,使用KVO监听,我们发现使用KVO监听的类多了一个NSKVONotifying_Person
(是使用Runtime动态创建的一个类,是person类的子类)
person2
的isa指向的是Person
,未使用KVO监听
当我们调用实例对象的isa
,会去类对象找到对应方法的实现。
-
person2
未使用KVO监听,所以直接调用Person
类对象的getter
和setter
方法。 -
person1
使用KVO监听,所以会去调用NSKVONotifying_Person
类对象的getter
和setter
方法。
2.1、大概的实现流程如下
#import "Person.h"
@interface NSKVONotifying_Person : Person
@end
@implementation NSKVONotifying_Person
- (void)setAge:(int)age
{
_NSSetIntValueAndNotify();
}
// 伪代码
void _NSSetIntValueAndNotify() {
[self willChangeValueForKey:@"age"];
[super setAge:age]; // 真正改变值
[self didChangeValueForKey:@"age"];
}
- (void)didChangeValueForKey:(NSString *)key {
// 通知监听器,某某属性值发生了改变
[oberser observeValueForKeyPath:key ofObject:self change:nil context:nil];
}
2.2 分析KVO底层实现
- 在监听之前后调用
object_getClass(<#id _Nullable obj#>)
NSLog(@"person1添加KVO监听之前 - person1 == %@ person2 == %@",
object_getClass(self.person1),
object_getClass(self.person2));
// 给person1对象添加KVO监听
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:@"123"];
NSLog(@"person1添加KVO监听之后 - person1 == %@ person2 == %@",
object_getClass(self.person1),
object_getClass(self.person2));
- 打印结果:在添加KVO后,
person1
的类发生了改变-->NSKVONotifying_Person
。
person1添加KVO监听之前 - person1 == Person person2 == Person
person1添加KVO监听之后 - person1 == NSKVONotifying_Person person2 == Person
- 在监听之前后调用
methodForSelector:<#(SEL)#>
NSLog(@"person1添加KVO监听之前 - person1 == %p person2 == %p",
[self.person1 methodForSelector:@selector(setAge:)],
[self.person2 methodForSelector:@selector(setAge:)]);
// 给person1对象添加KVO监听
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:@"123"];
NSLog(@"person1添加KVO监听之后 - person1 == %p person2 == %p",
[self.person1 methodForSelector:@selector(setAge:)],
[self.person2 methodForSelector:@selector(setAge:)]);
- 打印结果:在添加KVO后,
person1
的类地址发生了改变。
person1添加KVO监听之前 - person1 == 0x1004375e0 person2 == 0x1004375e0
person1添加KVO监听之后 - person1 == 0x100792216 person2 == 0x1004375e0
- 使用lldb指令打印地址对应的方法
p (IMP) 地址
,添加KVO监听之前改变age
值的方法就是[Person setAge:]
,监听KVO后的方法则是(Foundation
_NSSetIntValueAndNotify)Foundation框架下的
_NSSetIntValueAndNotify`方法
(lldb) p (IMP) 0x10ab575e0
(IMP) $0 = 0x000000010ab575e0 (`-[Person setAge:] at Person.m:13)
(lldb) p (IMP) 0x10aeb2216
(IMP) $1 = 0x000000010aeb2216 (Foundation`_NSSetIntValueAndNotify)
2.3、窥探Foundation框架下的_NSSetIntValueAndNotify
- 使用反编译工具hopper打开foundation文件,搜索
_NSSetIntValueAndNotify
可以看到
- 使用终端命令
nm Foundation | grep ValueAndNotify
打印,可以看到有Bool
、Char
、Double
、Float
、Int
、LongLong
、Long
、Object
、Point
、Range
、Rect
、Short
、Size
等等
思考
假如我们把上面Person
里面age
属性的类型换成Double
,那么KVO触发后,底层会调用哪个函数呢?
2.4、__NSSet XX ValueAndNotify的内部实现
- 调用
[self willChangeValueForKey:@"age"]
- 调用
[super setAge:age]
- 调用
[self didChangeValueForKey:@"age"]
- didChangeValueForKey内部会调用observer的
- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context;
方法
在Person类中实现
- (void)setAge:(int)age {
_age = age;
NSLog(@"setAge:");
}
- (void)willChangeValueForKey:(NSString *)key {
[super willChangeValueForKey:key];
NSLog(@"willChangeValueForKey");
}
- (void)didChangeValueForKey:(NSString *)key {
NSLog(@"didChangeValueForKey - begin");
[super didChangeValueForKey:key];
NSLog(@"didChangeValueForKey - end");
}
ViewController中实现代码
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[Person alloc] init];
self.person1.age = 1;
// 给person1对象添加KVO监听
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:@"123"];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.person1 setAge:21];
}
- (void)dealloc {
[self.person1 removeObserver:self forKeyPath:@"age"];
}
// 当监听对象的属性值发生改变时,就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"监听到%@的%@属性值改变了 - %@ - %@", object, keyPath, change, context);
}
打印结果:验证了上面说的内部实现步骤
willChangeValueForKey
setAge:
didChangeValueForKey - begin
监听到<Person: 0x600003df4330>的age属性值改变了 - {
kind = 1;
new = 21;
old = 1;
} - 123
didChangeValueForKey - end
面试
iOS 用什么方式实现对一个对象的KVO?(KVO的本质是什么?)
-
利用RuntimeAPI 动态生成一个子类,并且让instance对象的isa指向这个全新的子类。
-
当修改instance对象的属性是,会调用Foundation的_NSSetXXXValueAndNotify函数
-
调用[self willChangeValueForKey:@"age"]
调用 [super setAge:age]
调用 [self didChangeValueForKey:@"age"]didChangeValueForKey内部会调用observer的- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context;方法
如何手动触发KVO?
- 通过调用
willChangeValueForKey
和didChangeValueForKey
来触发
直接修改属性的值会触发KVO吗?
- 不会触发(是通过setter方法触发)
补充
1.1 isa指向何方
我们上面提到过,实例对象的isa
指向类对象,类对象的isa
指向元类对象。但是,我们通过KVO监听后产生的NSKVONotifying_Person
的isa
指向哪里呢?
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:@"123"];
NSLog(@"类对象 - person1 == %p person2 == %p",
object_getClass(self.person1), // self.person1.isa
object_getClass(self.person2)); // self.person2.isa
NSLog(@"元类对象 - person1 == %p person2 == %p",
object_getClass(object_getClass(self.person1)), // self.person1.isa.isa
object_getClass(object_getClass(self.person2))); // self.person2.isa.isa
打印结果:NSKVONotifying_Person
的isa
指向NSKVONotifying_Person
的metaClass对象
打印地址
类对象 - person1 == 0x600001dd3600 person2 == 0x10da2f158
元类对象 - person1 == 0x600001dd3690 person2 == 0x10da2f180
打印类名
类对象 - person1 == NSKVONotifying_Person person2 == Person
元类对象 - person1 == NSKVONotifying_Person person2 == Person
1.2 NSKVONotifying_Person和Person里面存的都是什么?
- 利用runtime获取类的方法
- (void)printMethodNamesOfClass:(Class)cls {
unsigned int count;
// 获得方法数组
Method *methodList = class_copyMethodList(cls, &count);
// 存储方法名
NSMutableString *methodNames = [NSMutableString string];
// 遍历所有的方法
for (int i = 0; i < count; i++) {
// 获得方法
Method method = methodList[i];
// 获得方法名
NSString *methodName = NSStringFromSelector(method_getName(method));
// 拼接方法名
[methodNames appendString:methodName];
[methodNames appendString:@", "];
}
// 释放
free(methodList);
// 打印方法名
NSLog(@"方法名 == %@ %@", cls, methodNames);
}
调用上面的方法打印得到:person1
,person2
里面包含的方法名
[self printMethodNamesOfClass:object_getClass(self.person1)];
[self printMethodNamesOfClass:object_getClass(self.person2)];
方法名 == NSKVONotifying_Person setAge:, class, dealloc, _isKVOA,
方法名 == Person age, setAge:,
1.3 NSKVONotifying_Person 里面的_isKVOA
、dealloc
、class
、setAge
是什么
猜想
- _isKVOA:
- (BOOL)_isKVOA {
return YES;
}
- dealloc:
- (void)dealloc {
// 收尾工作
}
- setAge:
- (void)setAge:(int)age {
// 调用
_NSSetIntValueAndNotify();
}
- class:
我们知道person1
通过KVO监听后生成了NSKVONotifying_Person
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:@"123"];
NSLog(@"person1 == %@, person2 == %@", object_getClass(self.person1), object_getClass(self.person2));
NSLog(@"person1 == %@, person2 == %@", [self.person1 class], [self.person2 class]);
打印结果:两个方法打印结果不一样,很显然object_getClass(self.person1)
这种方法是正确的,为什么[self.person1 class]
显示的却是NSKVONotifying_Person
类的父类呢?
- 我们创建的项目中并没有
NSKVONotifying_Person
这个类,暴露为用户,且NSKVONotifying_Person
这个类是Person
类的子类,在class
方法中直接返回了[Person class]
。 - 苹果的一种保护措施,上下一致(并没有创建
NSKVONotifying_Person
这个类)
person1 == NSKVONotifying_Person, person2 == Person
person1 == Person, person2 == Person
// 屏蔽内部实现,隐藏了NSKVONotifying_Person类的存在
- (Class)class {
return [Person class];
}
网友评论