KVC 詳解
KVC : 鍵值編碼(Key-Value Coding),它是一種通過key值訪問類屬性的機制,而不是通過setter/getter方法訪問。
1. KVC 常用方法
/*
取值
*/
// 通過key取值
- (id)valueForKey:(NSString *)key
// 通過路徑取值
- (nullable id)valueForKeyPath:(NSString *)keyPath
// 找不到key拋出異常
- (nullable id)valueForUndefinedKey:(NSString *)key
/*
修改
*/
// 對屬性進行簡單賦值
- (void)setValue:(nullable id)value forKey:(NSString *)key
// 根據(jù)路徑對屬性賦值
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath
// 找不到key的時候拋出異常
- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key
// 同時給多個屬性進行賦值
- (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues;
用代碼進行簡單的實驗
// Dog.m
@interface Dog ()
@property (nonatomic, copy) NSString *name;
@end
// Woman.m
@interface Woman ()
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) Dog *dog;
@end
@implementation Woman
- (instancetype)init
self = [super init];
if (self) {
Dog *dog = [[Dog alloc]init];
self.dog = dog;
}
return self;
}
- (void)logName {
NSLog(@"name:%@",self.name);
NSLog(@"dogName:%@",[self.dog valueForKey:@"name"]);
}
// 調(diào)用
Woman *woman = [[Woman alloc]init];
[woman setValue:@"大丫" forKey:@"name"];
[woman setValue:@"二哈" forKeyPath:@"dog.name"];
[woman logName];
// 打印結(jié)果
name:大丫
dogName: 二哈
2 .KVC 原理
- 當調(diào)用
- (void)setValue:(id)value forKey:(NSString *)key
時,KVC底層的執(zhí)行機制如下:- 首先搜索對應屬性的
setter
(依次尋找setKey: _setKey:)
方法 - 如果沒有找到屬性的
setter
方法,則會檢查+ (BOOL)accessInstanceVariablesDirectly
方法是否返回了YES(該方法默認返回YES),如果返回了YES, 則KVC機制會搜索類中是否存在該屬性的成員變量
,也就是_屬性名
,存在則對該成員變量
賦值。搜索成員變量名
的順序是_key
,_isKey
,key
,isKey
。
另外我們也可以通過重寫+ (BOOL)accessInstanceVariablesDirectly
方法返回NO,這個時候KVC機制就會調(diào)用- (void)setValue:(id)value forUndefinedKey:(NSString *)key
。 - 如果沒有找到
成員變量
,調(diào)用- (void)setValue:(id)value forUndefinedKey:(NSString *)key
。
- 首先搜索對應屬性的
/*
重寫`+ (BOOL)accessInstanceVariablesDirectly`方法返回 NO
*/
// Woman.m
@interface Woman (){
NSInteger _age;
}
+ (BOOL)accessInstanceVariablesDirectly{
return NO;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
NSLog(@"找不到key了");
}
// setValue:forKey:
Woman *woman = [[Woman alloc]init];
[woman setValue:@(18) forKey:@"age"];
// 打印結(jié)果
找不到key了
/*
找到了成員變量
*/
// Woman.m
@interface Woman (){
NSInteger _age; // 也可以是_age, _isAge, age, isAge
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
NSLog(@"找不到key了");
}
- (void)logAge {
NSLog(@"age:%ld",_age);
}
// setValue:forKey:
Woman *woman = [[Woman alloc]init];
[woman setValue:@"18" forKey:@"age"];
[woman logAge];
// 打印結(jié)果
age:18
/*
沒有成員變量,`+ (BOOL)accessInstanceVariablesDirectly`默認返回 YES
*/
// Woman.m
@interface Woman (){
// NSInteger _age;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
NSLog(@"找不到key了");
}
// setValue:forKey:
Woman *woman = [[Woman alloc]init];
[woman setValue:@"18" forKey:@"age"];
// 打印結(jié)果
找不到key了
- 當調(diào)用
- (id)valueForKey:(NSString *)key
時,KVC底層的執(zhí)行機制如下:- 首先按照
getKey
,key
,isKey
,_key
的順序查找方法,找到直接調(diào)用。如果是BOOL
、NSInteger
基本數(shù)據(jù)類型,會做NSNumber
類型轉(zhuǎn)換。 - 如果還是沒找到,如果類方法
accessInstanceVariablesDirectly
返回YES,那么按_key
,_isKey
,key
,iskey
的順序搜索成員變量名。返回NO,調(diào)用`valueForUndefinedKey. - 如果依舊沒有沒找到,調(diào)用
valueForUndefinedKey
。
- 首先按照
KVO 詳解
KVO:鍵值觀察者 (Key-Value Observer): KVO 是觀察者模式的一種實現(xiàn),觀察者A監(jiān)聽被觀察者B的某個屬性,當B的屬性發(fā)生更改時,A就會收到通知,執(zhí)行相應的方法。
1. KVO 相關(guān)方法
// 注冊觀察者
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
// 移除觀察者 (帶參數(shù))
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable void *)context API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
// 移除觀察者 (不帶參數(shù))
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
// 被觀察者屬性改變的回調(diào)方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context ;
用代碼進行簡單實驗
- (void)viewDidLoad {
[super viewDidLoad];
self.woman = [[Woman alloc]init];
// 注冊觀察者,被觀察的對象是woman的name屬性,觀察者為self
[self.woman addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}
// 監(jiān)聽屬性值發(fā)生改變后回調(diào)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"%@的%@改變了",object,keyPath);
}
// 點擊屏幕的時候改變woman的name
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.woman.name = @"二丫";
}
打印結(jié)果
<Woman: 0x60000024cab0>的name改變了
2. KVO 實現(xiàn)原理
我們來看看 apple官方文檔 對 KVO 具體實現(xiàn)的描述
Automatic key-value observing is implemented using a technique called isa-swizzling...
When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class.
KVO 使用了isa-swizzling
技術(shù)實現(xiàn)自動鍵值觀察... 當觀察者注冊對象的屬性時,觀察對象的isa指針被修改,指向中間類而不是真正的類。
中間類,一語道破了KVO 的內(nèi)在。
注冊完觀察者后,系統(tǒng)會做以下操作:
- 系統(tǒng)會動態(tài)創(chuàng)建了一個
Woman
的子類,類名是NSKVONotifying_Woman
。 -
NSKVONotifying_Woman
里會重寫被觀察屬性的setter
方法。在setter
方法里面實際上調(diào)用了Foundation框架的私有方法_NSSetLongLongValueAndNotify();
, 這個私有函數(shù)作用實際上相當于
[self willChangeValueForKey:@"age"];
_age = age;
[self didChangeValueForKey:@"age"]
在執(zhí)行賦值操作之前和之后,會通知所有觀察對象值的更改。
* 通知觀察者對象屬性發(fā)生改變需要兩個方法,willChangeValueForKey
和didChangevlueForKey
,顧名思義,一個是在被觀察者屬性改變之前調(diào)用,一個是在改變之后調(diào)用,然后在didChangevlueForKey
方法里面會調(diào)用observeValueForKey:ofObject:change:context:
方法。
- 修改被觀察者類的
isa
指針,讓這個isa
指針指向NSKVONotifying_Woman
類,所以調(diào)用被觀察的屬性的setter
方法時,實際上調(diào)用的是已經(jīng)重寫了的NSKVONotifying_Woman
類的setter
方法。
實際上apple為了隱藏自己偷偷摸摸建的這個類,他還偷偷重寫了class
方法,所以我們打印類名看到的依舊是Woman
類。但是,如果我們看對象的isa,則會看到實際指向的是NSKVONotifying_Woman
或者如果我們創(chuàng)建一個NSKVONotifying_Woman
類,編譯的時候,系統(tǒng)就會自己露出馬腳,告訴你KVO創(chuàng)建NSKVONotifying_Woman
類失敗 。
KVO failed to allocate class pair for name NSKVONotifying_Woman, automatic key-value observing will not work for this class`
我們又是怎么知道NSKVONotifying_Woman 調(diào)用了_NSSetLongLongValueAndNotify方法?還是用Woman類舉例
// Woman類中被監(jiān)聽的age屬性
@property (nonatomic, assign) NSInteger age;
// 以下是監(jiān)聽
Woman *woman = [[Woman alloc] init];
woman.age = 10;
Woman *woman2 = [[Woman alloc] init];
woman2.age = 20;
NSLog(@"添加監(jiān)聽之前 woman:%p woman2:%p", [woman methodForSelector:@selector(setAge:)], [woman2 methodForSelector:@selector(setAge:)]);
[woman addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
NSLog(@"添加監(jiān)聽之后 woman:%p woman2:%p", [woman methodForSelector:@selector(setAge:)], [woman2 methodForSelector:@selector(setAge:)]);
以上就是KVO內(nèi)部的實現(xiàn)原理。