一、KVO的初體驗
KVO的步驟:
- 1.添加觀察
- 2.
observe
回調 - 3.在合適位置更改觀察屬性的值
- 4.在
dealloc
里移除觀察
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [LGPerson new];
[self.person addObserver:self forKeyPath:@"nick" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.person.nick = [NSString stringWithFormat:@"%@+",self.person.nick];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"%@",change);
}
- (void)dealloc{
[self.person removeObserver:self forKeyPath:@"dateArray"];
}
二、KVO的其他用法
1、切換手動與自動
- 自動開關 (默認)
+ (BOOL) automaticallyNotifiesObserversForKey:(NSString *)key{
return YES;
}
- 手動開關
+ (BOOL) automaticallyNotifiesObserversForKey:(NSString *)key{
return NO;
}
- (void)setNick:(NSString *)nick{
[self willChangeValueForKey:@"nick"];
_nick = nick;
[self didChangeValueForKey:@"nick"];
}
2、路徑的處理
@implementation LGPerson
// 下載進度 -- writtenData/totalData
+ (NSSet<NSString *> *)keyPathsForValuesAffectingValueForKey:(NSString *)key{
NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];
if ([key isEqualToString:@"downloadProgress"]) {
NSArray *affectingKeys = @[@"totalData", @"writtenData"];
keyPaths = [keyPaths setByAddingObjectsFromArray:affectingKeys];
}
return keyPaths;
}
- (NSString *)downloadProgress{
if (self.writtenData == 0) {
self.writtenData = 1.0;
}
if (self.totalData == 0) {
self.totalData = 100;
}
return [[NSString alloc] initWithFormat:@"%f",1.0f*self.writtenData/self.totalData];
}
@end
@implementation LGViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [LGPerson new];
// 4: 路徑處理
// 下載的進度 = 已下載 / 總下載
[self.person addObserver:self forKeyPath:@"downloadProgress" options:(NSKeyValueObservingOptionNew) context:NULL];
}
@end
3、數組屬性的監聽
@interface LGPerson : NSObject
@property (nonatomic, strong) NSMutableArray *dateArray;
@end
@implementation LGViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [LGPerson new];
// 1: 數組觀察
self.person.dateArray = [NSMutableArray arrayWithCapacity:1];
[self.person addObserver:self forKeyPath:@"dateArray" options:(NSKeyValueObservingOptionNew) context:NULL];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// KVC 集合 array
[[self.person mutableArrayValueForKey:@"dateArray"] addObject:@"1"];
}
三、KVO的原理分析
首先我們斷點到self.person = [[LGPerson alloc] init]
后面,然后打印self.person的isa
是LFPerson
。
接著我們點擊
Step Next
,然后程序執行完[self.person addObserver:self forKeyPath:@"nickName" options:(NSKeyValueObservingOptionNew) context:NULL]
,我們再次查看self.person的isa
,卻發現是NSKVONotifying_LGPerson
由此,我們猜測:KVO的底層改變了
self.person的isa指向
,并動態的創建了LGPerson
的子類NSKVONotifying_LGPerson
接下來 我們添加如下代碼:
- (void)viewDidLoad {
[super viewDidLoad];
// KVO 底層原理
self.person = [[LGPerson alloc] init];
// 打印LGPerson的方法
[self printClassAllMethod:[LGPerson class]];
[self.person addObserver:self forKeyPath:@"nickName" options:(NSKeyValueObservingOptionNew) context:NULL];
// 打印LGPerson的方法
[self printClassAllMethod:[LGPerson class]];
// 打印NSKVONotifying_LGPerson的方法
Class cls = objc_getClass("NSKVONotifying_LGPerson");
[self printClassAllMethod:cls];
}
// 打印cls的方法
- (void)printClassAllMethod:(Class)cls{
unsigned int count = 0;
NSLog(@"以下為%@的方法列表:",NSStringFromClass(cls));
Method *methodList = class_copyMethodList(cls, &count);
for (int i = 0; i<count; i++) {
Method method = methodList[i];
SEL sel = method_getName(method);
IMP imp = class_getMethodImplementation(cls, sel);
NSLog(@"%@-%p",NSStringFromSelector(sel),imp);
}
free(methodList);
}
打印的結果:
從打印的結果來看:
添加KVO,沒有對LGPerson的進行添加方法的操作,而是對其
子類
動態的添加setNickName
方法,也就是從寫了父類的setNickName
方法,動態的添加了+(Class)class
, -(void)dealloc
方法。
接下來我們在dealloc里面斷點,在未執行remove
操作前,self.person的isa
指向NSKVONotifying_LGPerson
在執行
remove
操作后,self.person的isa
指向LGPerson
綜合上述,我們推測:
-
動態的創建NSKVONotifying_LGPerson子類,并添加方法
- 添加class : class的指向是LGPerson
2.添加setter(即: 重寫setter方法)
將對象的isa指向NSKVONotifying_LGPerson:object_setClass(self, newClass);
將觀察者信息保存在關聯屬性的NSKVO_AssiociateKey的可變數組中
-
在重寫的setter方法里面:
- 將消息轉發給父類,所以我們看到LGPerson里面的setNickName也會調用
- 消息發送(將觀察者作為消息的接受者, observeValueForKeyPath:ofObject:change:context: 作為 SEL)
在移除監聽時,將self.person的isa重新指向父類LGPerson