無論是在我們的今后的工作當中還是面試找工作當中,這兩個知識點是十分重要的,有些同學們對這方面的知識還是不是很了解,概念模糊,這里我整理下相關(guān)的內(nèi)容知識分享給大家。
一. KVO的實現(xiàn)原理
KVO相關(guān):
1\. iOS用什么方式來實現(xiàn)對一個對象的KVO乘综?(KVO的本質(zhì)是什么?)
2\. 如何手動出發(fā)KVO?
3\. 直接修改成員變量會觸發(fā)KVO么绝骚?
KVC相關(guān):
1\. 通過KVC修改屬性會觸發(fā)KVO么?
2\. KVC的賦值和取值過程是怎樣的祠够?原理是什么压汪?
- 什么是KVO?
KVO的全稱是Key-Value Observing古瓤,俗稱"鍵值監(jiān)聽"止剖,可以用于監(jiān)聽摸個對象屬性值得改變。
大家根據(jù)下面的圖更加深刻的來理解他們之間的關(guān)系
要監(jiān)聽Person中的age屬性落君,我們就創(chuàng)建一個observer用來監(jiān)聽age的變化穿香,當我們age一旦發(fā)生改變,就會通知observer绎速。
- KVO簡單的實現(xiàn)
我們先簡單的回顧一下 KVO的代碼實現(xiàn)皮获。
1.DLPerson.h 文件
///> DLPerson.h 文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface DLPerson : NSObject
@property (nonatomic, assign) int age;
@end
NS_ASSUME_NONNULL_END
- 在ViewController.m 文件使用Person類
///> ViewController.m 文件
#import "ViewController.h"
#import "DLPerson.h"
@interface ViewController ()
@property (nonatomic, strong) DLPerson *person1;
@property (nonatomic, strong) DLPerson *person2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[DLPerson alloc]init];
self.person1.age = 1;
self.person2 = [[DLPerson alloc]init];
self.person2.age = 2;
///> person1添加kvo監(jiān)聽
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 = 20;
self.person2.age = 30;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"監(jiān)聽到了%@的%@屬性發(fā)生了改變%@",object,keyPath,change);
}
- (void)dealloc{
///> 使用結(jié)束后記得移除
[self.person1 removeObserver:self forKeyPath:@"age"];
}
@end
以下是上面的代碼輸出結(jié)果
輸出結(jié)果:
監(jiān)聽到了<DLPerson: 0x6000033d4e40>的age屬性發(fā)生了改變- {
kind = 1;
new = 20;
old = 1;
}
///> 因為我們只監(jiān)聽了person1 所以只會輸出person1的改變。
- KVO存在的疑問
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// self.person1.age = 20;
[self.person1 setAge:20]; ///> 等同于self.person1.age = 20;
self.person2.age = 30;
[self.person2 setAge:20];///> 等同于self.person2.age = 20;
}
因為當我們在DLPerson中使用@property聲名一個屬性的時候會自動生成聲名屬性的set和get方法纹冤。如下代碼:
///> DLPerson.m文件
#import "DLPerson.h"
@implementation DLPerson
- (void)setAge:(int)age{
_age = age;
}
- (int)age{
return _age;
}
@end
既然person1和person2的本質(zhì)都是在調(diào)用set方法洒宝,就一定都會走在DLPerson類中的setAge這個方法购公。
那么問題來了,同樣走的是DLPerson類中的setAge方法雁歌,為什么person1就會走到,方法中而person2就不會呢宏浩?
- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context;
-
KVO的本質(zhì)分析(重點)
接下來我們探究一下兩個對象的本質(zhì),首先我們person1和person2的isa打印出來查看一下他們的實例對象isa指向的類對象是什么靠瞎?
我們會發(fā)現(xiàn)person1的isa指針打印出的是: NSKVONotifying_DLPerson
而person2的isa指針打印出來的是: DLPerson
person1和person2都是實例對象 所以person1和person2的isa指針指向的都是類對象比庄,
所以說,如果對象沒有添加KVO監(jiān)聽那么它的isa指向的就是自己原來的類對象乏盐,如下圖
person2.isa == DLPerson
當一個對象添加了KVO的監(jiān)聽時印蔗,當前對象的isa指針指向的就不是你原來的類,指向的是另外一個類對象丑勤,如下圖
person1.isa == NSKVONotifying_DLPerson
NSKVONotifying_DLPerson類是 Runtime動態(tài)創(chuàng)建的一個類,在程序運行的過程中產(chǎn)生的一個新的類吧趣。
NSKVONotifying_DLPerson類是DLPerson的一個子類法竞。
NSKVONotifying_DLPerson類存在自己的 setAge:、class强挫、dealloc、isKVOA…方法八匠。
當我們DLperson的實例對象調(diào)用setAge方法時梨树,
實例對象的isa指針找到類對象,然后在類類對象中尋找相應(yīng)的對象方法,如果有則調(diào)用,
如果沒有則去superclass指向的父類對象中尋找相應(yīng)的對象方法捷绒,如果有則調(diào)用崇渗,
如果未找到相應(yīng)的對象方法則會報:unrecognized selector sent to instance 錯誤
由于上圖可分析出我們的person1的isa指針指向的類對象是NSKVONotifying_DLPerson跟狱,并且NSKVONotifying_DLPerson中還帶有setAge: 方法,所以:
///> person1的setAge方法走的是NSKVONotifying_DLPerson類中的setAge方法,
///> 并且在KVO監(jiān)聽中實現(xiàn)了[superclass setAge:age];,
[self.person1 setAge:20];
///> person2的setAge方法走的是DLPerson中的setAge:方法闹啦,
[self.person2 setAge:30];
上次代碼所示琳袄,兩個實例對象person1和person2都走了DLPerson的setAge:方法,只是添加了KVO的person1在自己的setAge方法中添加了 其他操作。
///> NSKVONotifying_DLPerson.m 文件
#import "NSKVONotifying_DLPerson.h"
@implementation NSKVONotifying_DLPerson
- (void)setAge:(int)age{
_NSSetIntValueAndNotify(); ///> 文章末尾 知識點補充小結(jié)有此方法來源
}
void _NSSetIntValueAndNotify(){
[self willChangeValueForKey:@"age"];
[super setAge:age];
[self didChangeValueForKey:@"age"];
}
- (void)didChangeValueForKey:(NSString *)key{
///> 通知監(jiān)聽器 key發(fā)生了改變
[observe observeValueForKeyPath:key ofObject:self change:nil context:nil];
}
@end
- KVO的調(diào)用順序
由于我們的NSKVONotifying_DLPerson類不能參與編譯所以可以在 DLPerson.m中重寫它父類的方法代碼如下:
///> DLPerson.m文件
#import "DLPerson.h"
@implementation DLPerson
- (void)setAge:(int)age{
_age = age;
}
- (void)willChangeValueForKey:(NSString *)key{
[super willChangeValueForKey:key];
NSLog(@"willChangeValueForKey");
}
- (void)didChangeValueForKey:(NSString *)key{
NSLog(@"didChangeValueForKey - begin");
[super didChangeValueForKey:key];
NSLog(@"didChangeValueForKey - end");
}
@end
///> ViewController.m文件
#import "ViewController.h"
#import "DLPerson.h"
@interface ViewController ()
@property (nonatomic, strong) DLPerson *person1;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[DLPerson alloc]init];
self.person1.age = 10;
///> person1添加kvo監(jiān)聽
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.person1 setAge:20];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"監(jiān)聽到了%@的%@屬性發(fā)生了改變%@",object,keyPath,change);
}
- (void)dealloc{
///> 使用結(jié)束后記得移除
[self.person1 removeObserver:self forKeyPath:@"age"];
}
@end
輸出結(jié)果如下
willChangeValueForKey
didChangeValueForKey - begin
監(jiān)聽到了<DLPerson: 0x60000041afe0>的age屬性發(fā)生了改變{
kind = 1;
new = 20;
old = 10;
}
didChangeValueForKey - end
總結(jié):didChangeValueForKey:內(nèi)部會調(diào)用observer的observeValueForKeyPath:ofObject:change:context:方法
二. KVC的實現(xiàn)原理
1. 什么是KVC?
KVC的全稱key - value - coding塔橡,俗稱"鍵值編碼",可以通過key來訪問某個屬性
常見的API有:
- (void)setValue:(id)value forKey:(NSString *)key;
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
- (id)valueForKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
簡單的代碼實現(xiàn):
DLPerson 和 DLCat
///> DLPersin.h 文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
DLCat
*/
@interface DLCat : NSObject
@property (nonatomic, assign) int weight;
@end
/**
DLPerson
*/
@interface DLPerson : NSObject
@property (nonatomic, assign) int age;
@property (nonatomic, strong) DLCat *cat;
@end
NS_ASSUME_NONNULL_END
1.1 - (void)setValue:(id)value forKey:(NSString *)key;
///> ViewController.m 文件
- (void)viewDidLoad {
[super viewDidLoad];
DLPerson *person = [[DLPerson alloc]init];
[person setValue:@20 forKey:@"age"];
NSLog(@"%d",person.age);
}
1.1 - (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
///> ViewController.m 文件
- (void)viewDidLoad {
[super viewDidLoad];
DLPerson *person = [[DLPerson alloc]init];
person.cat = [[DLCat alloc]init];
[person setValue:@20 forKeyPath:@"cat.weight"];
NSLog(@"%d",person.age);
NSLog(@"%d",person.cat.weight);
}
setValue:(id)value forKeyPath:(NSString *)keyPath
和 setValue:(id)value forKey:(NSString *)key
的區(qū)別:
- keyPath 相當于根據(jù)路徑去尋找屬性末誓,一層一層往下找扯俱,
- key 是直接哪去屬性的名字設(shè)置迅栅,如果按路徑找會報錯
1.3 - (id)valueForKey:(NSString *)key;
///> ViewController.m 文件
- (void)viewDidLoad {
[super viewDidLoad];
DLPerson *person = [[DLPerson alloc]init];
person.age = 10;
NSLog(@"%@",[person valueForKey:@"age"]);
}
1.4 - (id)valueForKeyPath:(NSString *)keyPath;
///> ViewController.m 文件
- (void)viewDidLoad {
[super viewDidLoad];
DLPerson *person = [[DLPerson alloc]init];
person.age = 10;
NSLog(@"%@",[person valueForKey:@"cat.weight"]);
}
(id)valueForKey:(NSString *)key; 和 (id)valueForKeyPath:(NSString *)keyPath 的區(qū)別:
同理1.2-1.3
-
setValue:forKey:的原理
當我們設(shè)置setValue:forKey:時
首先會查找setKey:、_setKey: (按順序查找)
如果有直接調(diào)用
如果沒有畜号,先查看accessInstanceVariablesDirectly方法
+ (BOOL)accessInstanceVariablesDirectly{
return YES; ///> 可以直接訪問成員變量
// return NO; ///> 不可以直接訪問成員變量,
///> 直接訪問會報NSUnkonwKeyException錯誤
}
如果可以訪問會按照 _key、_isKey弄兜、key语泽、iskey的順序查找成員變量
找到直接復(fù)制
未找到報錯NSUnkonwKeyException錯誤
_key、_isKey视卢、key踱卵、iskey復(fù)制順序
///> DLPerson.h 文件
@interface DLPerson : NSObject{
@public
int _age;
int _isAge;
int age;
int isAge;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[DLPerson alloc]init];
///> person1添加kvo監(jiān)聽
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:nil];
///> 通過KVC修改person.age的值
[self.person1 setValue:@20 forKey:@"age"];
NSLog(@"------");
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"監(jiān)聽到了%@的%@屬性發(fā)生了改變%@",object,keyPath,change);
}
- (void)dealloc{
///> 使用結(jié)束后記得移除
[self.person1 removeObserver:self forKeyPath:@"age"];
}
在NSLog(@"------");位置打下短點注釋方式去查看各個值得復(fù)制順序
然后在控制臺中查看復(fù)制查找的順序就OK了,
DLPerson文件中的順序即使是調(diào)換了也無所謂据过。
-
valueForKey:的原理
如果可以訪問會按照 _key惋砂、_isKey、key绳锅、iskey的順序查找成員變量
找到直接復(fù)制
未找到報錯NSUnkonwKeyException錯誤
三. 知識點補充
- _NSSetIntValueAndNotify();方法來源
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[DLPerson alloc]init];
self.person1.age = 10;
self.person2 = [[DLPerson alloc]init];
self.person2.age = 20;
///> person1添加kvo監(jiān)聽
NSLog(@"person添加KVO之前 - person1:%@西饵, person2:%@",object_getClass(self.person1), object_getClass(self.person2));
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:nil];
NSLog(@"person添加KVO之前 - person1:%@, person2:%@",object_getClass(self.person1), object_getClass(self.person2));
}
輸出結(jié)果
person添加KVO之前 - person1:DLPerson鳞芙, person2:DLPerson
person添加KVO之后 - person1:NSKVONotifying_DLPerson眷柔, person2:DLPerson
由此可見在沒有 為person1添加KVO之前 person1.isa指針仍然是DLPerson
那么我們就可以使用- (IMP)methodForSelector:(SEL)aSelector;去查看實現(xiàn)方法的地址,的具體方法代碼如下:
///> person1添加kvo監(jiān)聽
NSLog(@"person添加KVO之前 - person1:%p原朝, person2:%p \n",[self.person1 methodForSelector:@selector(setAge:)], [self.person2 methodForSelector:@selector(setAge:)]);
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:nil];
NSLog(@"person添加KVO之后 - person1:%p驯嘱, person2:%p \n",[self.person1 methodForSelector:@selector(setAge:)], [self.person2 methodForSelector:@selector(setAge:)]);
}
輸出結(jié)果
person添加KVO之前 - person1:0x10852a560, person2:0x10852a560
person添加KVO之后 - person1:0x108883fc2喳坠, person2:0x10852a560
由此可見鞠评,在添加之前person1和person2實現(xiàn)的setAge方法是一個,添加之后person1的setAge方法就有了變化壕鹉。
然后我們打入斷點去查看實現(xiàn)的方法:
在控制臺中使用 p (IMP)方法地址 來打印得到方法的名稱剃幌。
所以我們在添加KVO之后的 setAge: 方法調(diào)用了 _NSSetIntValueAndNotify() 。
如果定義的屬性是類型是double則調(diào)用的是_NSSetDoubleValueAndNotify()
大家可以自己測試一下晾浴。
此方法在Foundtion框架中有對應(yīng)的
NSSetDoubleValueAndNotify()
NSSetIntValueAndNotify()
NSSetCharValueAndNotify()
...
- NSKVONotifying_DLPerson的isa指針指向哪里锥忿?
在 KVO的本質(zhì)分析 中我們得知,添加了KVO監(jiān)聽的實例對象isa指針指向了NSKVONotifying_DLPerson類怠肋, 那么NSKVONotifying_DLPerson的isa指針的指向敬鬓?
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[DLPerson alloc]init];
self.person1.age = 10;
self.person2 = [[DLPerson alloc]init];
self.person2.age = 20;
///> person1添加kvo監(jiān)聽
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:nil];
NSLog(@"類對象 - person1: %@<%p> person2: %@<%p>",
object_getClass(self.person1), ///> self.person1.isa 類名
object_getClass(self.person1), ///> self.person1.isa
object_getClass(self.person2), ///> self.person1.isa 類名
object_getClass(self.person2) ///> self.person1.isa
);
NSLog(@"元類對象 - person1: %@<%p> person2: %@<%p>",
object_getClass(object_getClass(self.person1)), ///> self.person1.isa.isa 類名
object_getClass(object_getClass(self.person1)), ///> self.person1.isa.isa
object_getClass(object_getClass(self.person2)), ///> self.person2.isa.isa 類名
object_getClass(object_getClass(self.person2)) ///> self.person2.isa.isa
);
}
輸出結(jié)果
類對象 - person1: NSKVONotifying_DLPerson<0x6000002cef40> person2: DLPerson<0x1002c9048>
元類對象 - person1: NSKVONotifying_DLPerson<0x6000002cf210> person2: DLPerson<0x1002c9020>
結(jié)果發(fā)現(xiàn):每一個類對象的地址是不一樣的,而且元類對象的地址也不一樣的,所以我們可以認為 NSKVONotifying_DLPerson類有自己的元類對象钉答, NSKVONotifying_DLPerson.isa指向著自己的元類對象础芍。
四. 面試題答案
- iOS用什么方式實現(xiàn)對一個對象的KVO?(KVO的本質(zhì)是什么数尿?)
利用RuntimeAPI動態(tài)生成一個子類仑性,并且讓instance對象的isa指向這個全新的子類
當修改instance對象的屬性時,會調(diào)用Foundation的_NSSetXXXValueAndNotify函數(shù)
willChangeValueForKey:
父類原來的setter
didChangeValueForKey:
內(nèi)部會觸發(fā)監(jiān)聽器(Oberser)的監(jiān)聽方法(observeValueForKeyPath:ofObject:change:context:)
- 如何手動觸發(fā)KVO右蹦?
手動調(diào)用willChangeValueForKey:和didChangeValueForKey:
- 直接修改成員變量會觸發(fā)KVO么诊杆?
不會觸發(fā)KVO,因為直接修改成員變量并沒有走set方法何陆。
KVC相關(guān):
- 通過KVC修改屬性會觸發(fā)KVO么晨汹?
會觸發(fā)KVO,如上流程圖
- KVC的賦值和取值過程是怎樣的贷盲?原理是什么淘这?
如上流程圖
- KVC可以修改私有屬性和私有成員變量嗎?
可以
參考文檔:
iOS底層原理總結(jié)–OC對象的本質(zhì)(一) - 掘金
iOS底層原理總結(jié)–OC對象的本質(zhì)(二) - 掘金
iOS底層原理總結(jié)–OC對象的分類:instance、class巩剖、meta-calss對象的isa和superclass - 掘金