iOS KVO的使用以及原理
簡介
KVO:(Key - Value - Observer) 鍵值觀察者,是觀察者設(shè)計模式的一種具體實現(xiàn)(C層和M層的通信)
KVO觸發(fā)機制:
一個對象(觀察者),檢測另一個對象(被觀察者)的某屬性是否發(fā)生變化,若被監(jiān)測的屬性發(fā)生了更改,會觸發(fā)觀察者的一個方法(方法名固定,類似代理方法)
KVO的使用
//
// ViewController.m
// kvoTest
//
// Created by Admin on 2021/12/7.
//
#import "ViewController.h"
@interface Person:NSObject
@property (nonatomic,assign) int age;
@end
@implementation Person
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *p1 = [[Person alloc] init];
p1.age = 1;
// self 監(jiān)聽 p1的 age屬性
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[p1 addObserver:self forKeyPath:@"age" options:options context:nil];
p1.age = 10;
[p1 removeObserver:self forKeyPath:@"age"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"監(jiān)聽到%@的%@改變了%@", object, keyPath,change);
}
@end
使用方法
- 注冊觀察者(為被觀察這指定觀察者以及被觀察者屬性)(
addObserver: forKeyPath:
) - 實現(xiàn)回調(diào)方法(
observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
) - 觸發(fā)回調(diào)方法(
通過點語法或者set方法又或者KVC賦值
) - 移除觀察者(
removeObserver: forKeyPath:
)
<aside>
?? 常見Crash如下
- 觀察者未實現(xiàn)監(jiān)聽方法(
觀察者對象 observeValueForKeyPath:ofObject:change:context: 未實現(xiàn)
) - 未及時移除觀察者(
Thread 1: EXC_BAD_ACCESS (code=1, address=0x105e0fee02c0)
) - 多次移除(
Cannot remove an observer for the key path “age” from because it is not registered as an observer
)
</aside>
KVO的原理
當(dāng)一個對象使用了
KVO
監(jiān)聽汹想,iOS系統(tǒng)會修改這個對象的isa
指針切厘,改為指向一個全新的通過Runtime
動態(tài)創(chuàng)建的子類月褥,子類擁有自己的set
方法實現(xiàn),set
方法實現(xiàn)內(nèi)部會順序調(diào)用willChangeValueForKey
方法谆刨、原來的setter
方法實現(xiàn)戚绕、didChangeValueForKey
方法纹坐,而didChangeValueForKey
方法內(nèi)部又會調(diào)用監(jiān)聽器的observeValueForKeyPath:ofObject:change:context
:監(jiān)聽方法。
驗證代碼
//
// ViewController.m
// kvoTest
//
// Created by Admin on 2021/12/7.
//
#import "ViewController.h"
#import <objc/message.h>
@interface Person:NSObject
@property (nonatomic,assign) int age;
@end
@implementation Person
- (void)setAge:(int)age
{
NSLog(@"setAge:");
_age = age;
}
- (void)willChangeValueForKey:(NSString *)key
{
NSLog(@"willChangeValueForKey: - begin");
[super willChangeValueForKey:key];
NSLog(@"willChangeValueForKey: - end");
}
- (void)didChangeValueForKey:(NSString *)key
{
NSLog(@"didChangeValueForKey: - begin");
[super didChangeValueForKey:key];
NSLog(@"didChangeValueForKey: - end");
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *p1 = [[Person alloc] init];
Person *p2 = [[Person alloc] init];
p1.age = 1;
// self 監(jiān)聽 p1的 age屬性
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[p1 addObserver:self forKeyPath:@"age" options:options context:nil];
[self printMethods: object_getClass(p2)];
[self printMethods: object_getClass(p1)];
p1.age = 10;
[p1 removeObserver:self forKeyPath:@"age"];
}
- (void) printMethods:(Class)cls
{
unsigned int count ;
Method *methods = class_copyMethodList(cls, &count);
NSMutableString *methodNames = [NSMutableString string];
[methodNames appendFormat:@"%@ - ", cls];
for (int i = 0 ; i < count; i++) {
Method method = methods[i];
NSString *methodName = NSStringFromSelector(method_getName(method));
[methodNames appendString: methodName];
[methodNames appendString:@" "];
}
NSLog(@"%@",methodNames);
free(methods);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"監(jiān)聽到%@的%@改變了%@", object, keyPath,change);
}
@end
KVO如何手動觸發(fā)
被監(jiān)聽的屬性的值被修改時舞丛,就會自動觸發(fā)KVO耘子。如果想要手動觸發(fā)KVO,則需要我們自己調(diào)用
willChangeValueForKey
和didChangeValueForKey
方法即可在不改變屬性值的情況下手動觸發(fā)KVO球切,并且這兩個方法缺一不可
驗證代碼
- (void)viewDidLoad {
[super viewDidLoad];
Person *p1 = [[Person alloc] init];
Person *p2 = [[Person alloc] init];
p1.age = 1;
// self 監(jiān)聽 p1的 age屬性
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[p1 addObserver:self forKeyPath:@"age" options:options context:nil];
[self printMethods: object_getClass(p2)];
[self printMethods: object_getClass(p1)];
// p1.age = 10;
[p1 willChangeValueForKey:@"age"];
[p1 didChangeValueForKey:@"age"];
[p1 removeObserver:self forKeyPath:@"age"];
}
?? **willChangeValueForKey
和didChangeValueForKey
它們分別做了什么谷誓?**
willChangeValueForKey
是為了通過KVC方法取得舊值
didChangeValueForKey
中會調(diào)用監(jiān)聽器的監(jiān)聽方法,最終來到監(jiān)聽者的observeValueForKeyPath
方法中