KVO、KVC源碼解讀

KVO

KVO是蘋果Fundation框架提供的一套鍵值監聽API,全稱是Key-Value Observing,可以用于監聽某個對象屬性值的改變

使用

//定義類
@interface Person : NSObject
@property (assign, nonatomic) int age;
@property (assign, nonatomic) int height;
@end

//使用類
self.person = [[Person alloc] init];
// 給person對象添加KVO監聽
NSLog(@"person添加KVO監聽之前 - %@", object_getClass(self.person));
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person addObserver:self forKeyPath:@"age" options:options context:@"123"];
[self.person addObserver:self forKeyPath:@"height" options:options context:@"456"];
NSLog(@"person添加KVO監聽之后 - %@", object_getClass(self.person));

// 當監聽對象的屬性值發生改變時,就會調用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    NSLog(@"監聽到%@的%@屬性值改變了 - %@ - %@", object, keyPath, change, context);
}
//當被監聽的對象age、height發生變化的時候上邊的回調就會打印,這里點擊了屏幕
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.person.age = 20;
    self.person.height = 20;
}

原理

  • 在運行時,系統會為調用[addObserver: forKeyPath: options: context:]方法的類,動態的派生出一個名字是NSKVONotifying_xxx的子類,比如上邊的Person,系統會動態的生成NSKVONotifying_Person,繼承于Person。
上文使用的代碼,打印的類名
2019-12-29 21:08:23.555903+0800 test[11661:1118994] person添加KVO監聽之前 - MJPerson
2019-12-29 21:08:23.556300+0800 test[11661:1118994] person添加KVO監聽之后 - NSKVONotifying_MJPerson
  • 重寫了set方法,內部調用了_NSSetIntValueAndNotify,_NSSetIntValueAndNotify內部調用了-willChangeValueForKey和-didChangeValueForKey,最后調用observeValueForKeyPath:去通知監聽者。
比如person類
- (void)setAge:(int)age
{
    _NSSetIntValueAndNotify();
}

// 偽代碼
void _NSSetIntValueAndNotify()
{
    [self willChangeValueForKey:@"age"];
    [super setAge:age];
    [self didChangeValueForKey:@"age"];
}

- (void)didChangeValueForKey:(NSString *)key
{
    // 通知監聽器,某某屬性值發生了改變
    [oberser observeValueForKeyPath:key ofObject:self change:nil context:nil];
}

  • 重寫了class方法,通過class方法直接返回person,不然就是返回NSKVONotifying_Person,對使用方的通明化。
  • 重寫了dealloc方法,類釋放時候,做一些清除釋放操作
  • 增加了_isKVOA方法,返回YES,則使用kvo。

證明

  • 通過xcode的Fundation框架,查看_NSSet*AndNotify的存在。


  • 通過代碼,查看NSKVONotifying_Person的方法列表。

- (void)printMethodNamesOfClass:(Class)cls
{
    unsigned int count;
    // 獲得方法數組
    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);
}
//輸出
2019-12-29 21:21:04.068859+0800 Interview01[11719:1127666] NSKVONotifying_Person setAge:, class, dealloc, _isKVOA,

面試題

  • iOS用什么方式實現對一個對象的KVO?(KVO的本質是什么?)
    利用RuntimeAPI動態生成一個子類,并且讓instance對象的isa指向這個全新的子類
    當修改instance對象的屬性時,會調用Foundation的_NSSetXXXValueAndNotify函數
    willChangeValueForKey:
    父類原來的setter
    didChangeValueForKey:
    內部會觸發監聽器(Oberser)的監聽方法( observeValueForKeyPath:ofObject:change:context:)

  • 如何手動觸發KVO?
    手動調用willChangeValueForKey:和didChangeValueForKey:

  • 直接修改成員變量會觸發KVO么?
    不會觸發KVO

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; 

setValue:forKey:的原理

valueForKey:的原理

KVC總結:

基于上邊的原理圖,我們通過代碼去實際檢驗一下,可以看出程序是按照著上述的順序去查找方法,所以我們可以認為

  • 在我們沒有聲明任何變量的情況下,只是實現了setKey的方法,能夠觸發KVO。
  • 只有成員變量的情況下,通過setValue: forkey:方法也能夠觸發KVO。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。