【原創(chuàng)博文,轉(zhuǎn)載請注明出處!】
之前做iOS開發(fā)的時候經(jīng)常使用KVO來監(jiān)聽對象屬性值的變化去執(zhí)行一些操作,但是從未思考過KVO底層是怎么實(shí)現(xiàn)的,今天有空研究一下。
寫個簡單demo驗(yàn)證開始探索之路:
#import "Person.h"
@implementation Person
- (void)setAge:(int)age
{
_age = age;
}
@end
給新建的Person類創(chuàng)建對象person1與person2,并對person1的age屬性添加observer(鍵值觀察)。
- (void)viewDidLoad {
[super viewDidLoad];
self.person1 = [[Person alloc] init];
self.person1.age = 1;
self.person2 = [[Person alloc] init];
self.person2.age = 2;
// 給person1對象添加KVO監(jiān)聽
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person1 addObserver:self forKeyPath:@"age" options:options context:@"觀察者"];
}
// 當(dāng)監(jiān)聽對象的屬性值發(fā)生改變時,就會調(diào)用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"監(jiān)聽到%@的%@屬性值改變了 - %@ - %@", object, keyPath, change, context);
}
為了測試方便,在- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
方法里面修改person1的age屬性值。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.person1.age = 22;
// self.person2.age = 22;
}
控制器銷毀了,應(yīng)當(dāng)及時移除觀察者。
- (void)dealloc {
[self.person1 removeObserver:self forKeyPath:@"age"];
}
觸摸手機(jī)屏幕,log日志如下,一切盡在意料之中。
2018-08-01 22:19:39.933946+0800 Interview01[54395:4839324] 監(jiān)聽到<Person: 0x60000000c910>的age屬性值改變了 - {
kind = 1;
new = 22;
old = 1;
} - 觀察者
是的,上面關(guān)于KVO的使用過程演示完了,如果到此結(jié)束,也就沒啥好記錄的了。但是這次探究的是KVO做了啥,所以還得講好長一堆。。。話。
先來看看添加觀察者之后person1的isa指針與未添加觀察者person2的isa指針異同,結(jié)果如下圖所示:
驚奇地發(fā)現(xiàn)添加觀察者之后,person1的isa指針居然由Person
變成了NSKVONotifying_Person
,我們知道實(shí)例對象(person1、person2)的isa指針指向類對象(關(guān)于isa指針方面的知識,可以參考這篇文章,講得比較容易理解。談?wù)勎覍bjective-C對象本質(zhì)的理解),這樣一來也就說明person1的直接類對象并不是Person
,而是NSKVONotifying_Person
這個類。所以可以猜測:當(dāng)我們?yōu)閜erson1的屬性添加觀察者之后,系統(tǒng)幫動態(tài)地位我們創(chuàng)建了一個繼承自Person
的類NSKVONotifying_Person
,在NSKVONotifying_Person
中執(zhí)行了某些操作,觸發(fā)了- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
監(jiān)聽方法。
也可以通過object_getClass
獲取isa指針指向的關(guān)系。
NSString *name1 = NSStringFromClass(object_getClass(self.person1));
NSString *name2 = NSStringFromClass(object_getClass(self.person2));
NSLog(@"name1_class:%@",name1);
NSLog(@"name2_class:%@",name2);
// 2018-08-01 23:05:40.811525+0800 Interview01[55316:5109057] name1_class:NSKVONotifying_Person
// 2018-08-01 23:05:40.812380+0800 Interview01[55316:5109057] name2_class:Person
發(fā)現(xiàn)了新的類 NSKVONotifying_Person
,可以通過底層的方法class_copyMethodList
研究一下NSKVONotifying_Person
都有哪些方法。
- (void)printMethodNamesOfClass:(Class)cls
{
unsigned int count;
// 獲得方法數(shù)組
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);
}
2018-08-01 23:17:42.980971+0800 Interview01[55561:5179836] NSKVONotifying_Person setAge:, class, dealloc, _isKVOA,
2018-08-01 23:17:42.981241+0800 Interview01[55561:5179836] Person setAge:, age,
所以NSKVONotifying_Person實(shí)現(xiàn)了“setAge: class dealloc _isKVOA”這四個方法。
關(guān)于setAge:方法,內(nèi)部調(diào)用了Foundation框架下的“_NSSetIntValueAndNotify”方法,而“_NSSetIntValueAndNotify”方法內(nèi)部實(shí)現(xiàn)則大致為:
重寫class
方法是蘋果的陰謀吧。正常情況下通過[object class]可以得到object的類對象,但是我們嘗試對person1執(zhí)行class
方法,得到的類對象仍舊為Person
,而換成更底層的方法object_getClass(self.person1)
則得到類對象NSKVONotifying_Person
,因此這里重寫了class
方法,也就是Apple為了掩人耳目,掩蓋事實(shí),想迷惑一下開發(fā)者,隱藏動態(tài)新建的一個Person子類。
重寫dealloc
方法做一些收尾的工作,釋放某些變量,移除某些依賴等。
_isKVOA
也就是對屬性做個類型區(qū)分作用。
didChangeValueForKey:
方法內(nèi)部會調(diào)用observer的observeValueForKeyPath:ofObject:change:context:
方法。
問題:
1、iOS用什么方式實(shí)現(xiàn)對一個對象的KVO?(KVO的本質(zhì)是什么?)
利用RuntimeAPI動態(tài)生成一個子類,并且讓instance對象的isa指向這個全新的子類;
當(dāng)修改instance對象的屬性時,會調(diào)用Foundation的_NSSetXXXValueAndNotify函數(shù)
①willChangeValueForKey:
②父類原來的setter
③didChangeValueForKey:
didChangeValueForKey
內(nèi)部會觸發(fā)監(jiān)聽器(Oberser)的監(jiān)聽方法( observeValueForKeyPath:ofObject:change:context:)
2、如何手動觸發(fā)KVO?
對監(jiān)聽的對象手動調(diào)用下面兩行代碼即可。
[self.person1 willChangeValueForKey:@"age"];
[self.person1 didChangeValueForKey:@"age"];
3、KVO與代理的效率問題?
KVO的效率比代理的效率低,因?yàn)镵VO需要動態(tài)地生成一個類NSKVONotifying_className
,耗時。
4、使用KVC給對象屬性賦值,能不能觸發(fā)KVO?
可以觸發(fā)KVO。因?yàn)镵VC本質(zhì)上會調(diào)用屬性的setXxx:方法。
5、直接修改成員變量會觸發(fā)KVO嘛?
不會觸發(fā)KVO,因?yàn)樾薷某蓡T變量不會觸發(fā)set方法。
KVC
KVC的全稱是Key-Value Coding
,俗稱“鍵值編碼”,可以通過一個key來訪問對象的某個屬性。
常見的API有下面四個
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
- (void)setValue:(id)value forKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
- (id)valueForKey:(NSString *)key;
那么KVC的賦值和取值過程是怎樣的?原理是什么?
KVC在賦值的時候,按照setKey:、_setKey:的順序查找對象是否有對應(yīng)的方法實(shí)現(xiàn),如果有的話就傳遞參數(shù)并調(diào)用方法,如過這兩個方法都沒有實(shí)現(xiàn),則調(diào)用對象的+ (BOOL)accessInstanceVariablesDirectly
方法,查看是否允許直接訪問成員變量。下面我們證明之:
A:新建一個Person類,不添加任何屬性,實(shí)現(xiàn)- (void)setAge:(NSUInteger)age
、- (void)_setAge:(NSUInteger)age
方法。初始化一個Person實(shí)例并對其進(jìn)行KVC賦值,看系統(tǒng)調(diào)用結(jié)果。
#import "Person.h"
@implementation Person
- (void)setAge:(NSUInteger)age{
NSLog(@"setAge : %lu",(unsigned long)age);
}
- (void)_setAge:(NSUInteger)age{
NSLog(@"_setAge : %lu",(unsigned long)age);
}
@end
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Person.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc] init];
[person setValue:@20 forKey:@"age"];
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
//log日志:
//2018-08-02 22:59:02.559184+0800 KVC[9356:451128] setAge : 20
B:將Person類中的- (void)setAge:(NSUInteger)age
注釋掉,保留- (void)_setAge:(NSUInteger)age
,看系統(tǒng)調(diào)用結(jié)果。
#import "Person.h"
@implementation Person
//- (void)setAge:(NSUInteger)age{
// NSLog(@"setAge : %lu",(unsigned long)age);
//}
- (void)_setAge:(NSUInteger)age{
NSLog(@"_setAge : %lu",(unsigned long)age);
}
@end
//log日志:
//2018-08-02 23:15:08.754741+0800 KVC[9662:544138] _setAge : 20
由以上結(jié)果可見,我們調(diào)用方法
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
或
- (void)setValue:(id)value forKey:(NSString *)key;
時,OC底層依次查找了setKey:
或_setKey:
方法。
如果沒有setKey:
或_setKey:
方法怎么辦?
沒有實(shí)現(xiàn)setKey:
或_setKey:
方法,系統(tǒng)將查看+(BOOL)accessInstanceVariablesDirectly
方法的返回結(jié)果(該方法默認(rèn)返回YES),這個方法決定是否可以直接訪問成員變量key。
注意:如果+(BOOL)accessInstanceVariablesDirectly
方法返回了NO
,那么就會調(diào)用setValue:forUndefinedKey:
并拋出異常NSUnknownKeyException!
注意,這里面為什么提到對象的成員變量,而不是屬性呢?
如果是屬性的話,系統(tǒng)自動幫我們實(shí)現(xiàn)了set方法,所以KVC總是可以找到它需要的`setKey:`方法。如果是成員變量,系統(tǒng)就不會為你實(shí)現(xiàn)set方法了。
KVC在訪問成員變量時也嚴(yán)格按照_key
、_isKey
、key
、isKey
的順序查找。下面我們將上面代碼中- (void)setAge:(NSUInteger)age
、- (void)_setAge:(NSUInteger)age
注釋掉,并添加四個成員變量_age
、_isAge
、age
、isAge
。
通過設(shè)置斷點(diǎn)觀察對象成員變量值得變化,證明了 ‘嚴(yán)格按照_key
、_isKey
、key
、isKey
的順序查找’的結(jié)論,后面還有兩張圖自己腦補(bǔ)一下唄(^^)
因此KVC的賦值過程可用下圖歸納:
知道了KVC的賦值過程,那KVC的取值過程又是怎樣的?
- (id)valueForKey:(NSString *)key;
或 - (id)valueForKeyPath:(NSString *)keyPath;
方法取值的時候,按照getKey、key、isKey、_key的順序查找對應(yīng)方法,一旦找到就調(diào)用方法獲取值。如果沒有找到以上四個方法,同樣會調(diào)用+(BOOL)accessInstanceVariablesDirectly
方法,看是否具備直接訪問成員變量的權(quán)限。與KVC的賦值過程相同,在查找成員變量的時候,也是嚴(yán)格按照 _key
、_isKey
、key
、isKey
的順序查找的。找到了就直接取值,都沒有找到的話,后果也是相同的,即調(diào)用setValue:forUndefinedKey:
并拋出異常NSUnknownKeyException*!
demo
#import "Person.h"
@interface Person ()
//{
// int age;
// int isAge;
//// int _age;
// int _isAge;
//}
@end
@implementation Person
+ (BOOL)accessInstanceVariablesDirectly{
return YES;
}
- (int)getAge{
NSLog(@"getAge");
return 5;
}
- (int)age{
NSLog(@"age");
return 10;
}
- (int)isAge{
NSLog(@"isAge");
return 15;
}
- (int)_age{
NSLog(@"_age");
return 20;
}
//- (void)setAge:(NSUInteger)age{
// NSLog(@"setAge : %lu",(unsigned long)age);
//}
//
//- (void)_setAge:(NSUInteger)age{
// NSLog(@"_setAge : %lu",(unsigned long)age);
//}
@end
int main(int argc, char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc] init];
[person valueForKey:@"age"];
NSLog(@".....");
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
測試的時候,依次對getKey、key、isKey、_key方法進(jìn)行注釋,通過log日志可見KVC的取值時候調(diào)用的方法順序依次為:getKey
、key
、isKey
、_key
。
關(guān)于KVC的取值過程,千言萬語匯成下面一張圖??