收錄:原文地址
KVO
在我們實際開發(fā)之中運用非常之多,很多開發(fā)者都知道原理鳄炉!但是這些原理是如何來的搜骡,一般都是淺嘗輒止记靡。這個篇章我會從Swift
入手分析,探索KVO
底層源碼.希望讓讀者真正掌握這一塊底層空凸,知其然而知其所以然呀洲!
KVO簡介
首先我們從KVO
的三部曲開始
// 1: 添加觀察
person.addObserver(self, forKeyPath: "name", options: .new, context: nil)
// 2: 觀察響應(yīng)回調(diào)
override func observeValue(forKeyPath keyPath:, of object:, change: , context:){}
// 3: 移除觀察
person.removeObserver(self, forKeyPath: "name")
其實我們也知道两嘴,就是平時在開發(fā)的時候族壳,我們也可以通過計算型屬性也可以直接觀察
var name: String = ""{
willSet{
print(newValue)
}
didSet{
print(oldValue)
}
}
問題來了:這兩者有什么關(guān)系仿荆?
KVO與計算型屬性的關(guān)系
下面我們開始分析拢操,首先感謝蘋果開源精神,在Github可以直接下載杠园,我們通過 Swift
源碼展開分析
public func willChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>) {
(self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath))
}
public func willChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: __owned KeyPath<Self, Value>) {
(self as! NSObject).willChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath))
}
public func willChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void {
(self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set)
}
public func didChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>) {
(self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath))
}
public func didChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: __owned KeyPath<Self, Value>) {
(self as! NSObject).didChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath))
}
public func didChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void {
(self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set)
}
-
willChangeValue
和didChangeValue
作為數(shù)據(jù)改變的兩個重要的方法 - 我們通過這兩個方法繼續(xù)展開分析
class Target : NSObject, NSKeyValueObservingCustomization {
// This dynamic property is observed by KVO
@objc dynamic var objcValue: String
@objc dynamic var objcValue2: String {
willSet {
willChangeValue(for: \.objcValue2)
}
didSet {
didChangeValue(for: \.objcValue2)
}
}
}
- 很明顯的繼承關(guān)系來自
NSObject
- 實現(xiàn)了
NSKeyValueObservingCustomization
的協(xié)議
public protocol NSKeyValueObservingCustomization : NSObjectProtocol {
static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath>
static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool
}
- 這也是我們兩個非常重要的方法惕橙,平時在開發(fā)也是很有利的方法,
keyPathsAffectingValue
能夠建立keyPath
的依賴肚逸,例如兩個屬性的變化同時影響一個重要屬性的改變:進度 = 下載量 / 總量
-
automaticallyNotifiesObservers
自動開關(guān) - 很明顯我們的計算型屬性在
willSet
里面就調(diào)用willChangeValue
朦促,didSet
調(diào)用didChangeValue
务冕,的確我們計算型屬性是和我們KVO相關(guān)方法是有所關(guān)聯(lián)混滔,這里也直接證明坯屿! - OK领跛,我們探索完這個問題,我們摸著這條線繼續(xù)探索
KVO底層
喊括!
KVO底層
這里說明一下郑什,本篇章的貼出的源碼沒有給大家省略,目的是想讓大家認真閱讀钝满,自己對照學習弯蚜。當然可能中間我也忽略過一些細節(jié)剃法,源碼直接貼出來方便自己理解
添加觀察
person.addObserver(self, forKeyPath: "name", options: .new, context: nil)
現(xiàn)在我們開始探索底層源碼:
- (void) addObserver: (NSObject*)anObserver
forKeyPath: (NSString*)aPath
options: (NSKeyValueObservingOptions)options
context: (void*)aContext
{
GSKVOInfo *info;
GSKVOReplacement *r;
NSKeyValueObservationForwarder *forwarder;
NSRange dot;
setup();
[kvoLock lock];
// Use the original class
r = replacementForClass([self class]);
/*
* Get the existing observation information, creating it (and changing
* the receiver to start key-value-observing by switching its class)
* if necessary.
*/
info = (GSKVOInfo*)[self observationInfo];
if (info == nil)
{
info = [[GSKVOInfo alloc] initWithInstance: self];
[self setObservationInfo: info];
object_setClass(self, [r replacement]);
}
/*
* Now add the observer.
*/
dot = [aPath rangeOfString:@"."];
if (dot.location != NSNotFound)
{
forwarder = [[NSKeyValueObservationForwarder alloc]
initWithKeyPath: aPath
ofObject: self
withTarget: anObserver
context: aContext];
[info addObserver: anObserver
forKeyPath: aPath
options: options
context: forwarder];
}
else
{
[r overrideSetterFor: aPath];
[info addObserver: anObserver
forKeyPath: aPath
options: options
context: aContext];
}
[kvoLock unlock];
}
-
中間
replacementForClass
做了一些處理:- 創(chuàng)建了一個動態(tài)子類名字:"NSKVONotifing_原類的名字"
- 添加了
class收厨、set帽氓、dealloc
方法 - 原類的
isa
與動態(tài)isa
切換
由原來的觀察者進行遷移到
GSKVOInfo
- (void) addObserver: (NSObject*)anObserver
forKeyPath: (NSString*)aPath
options: (NSKeyValueObservingOptions)options
context: (void*)aContext
{
GSKVOPathInfo *pathInfo;
GSKVOObservation *observation;
unsigned count;
if ([anObserver respondsToSelector:
@selector(observeValueForKeyPath:ofObject:change:context:)] == NO)
{
return;
}
[iLock lock];
pathInfo = (GSKVOPathInfo*)NSMapGet(paths, (void*)aPath);
if (pathInfo == nil)
{
pathInfo = [GSKVOPathInfo new];
// use immutable object for map key
aPath = [aPath copy];
NSMapInsert(paths, (void*)aPath, (void*)pathInfo);
[pathInfo release];
[aPath release];
}
observation = nil;
pathInfo->allOptions = 0;
count = [pathInfo->observations count];
while (count-- > 0)
{
GSKVOObservation *o;
o = [pathInfo->observations objectAtIndex: count];
if (o->observer == anObserver)
{
o->context = aContext;
o->options = options;
observation = o;
}
pathInfo->allOptions |= o->options;
}
if (observation == nil)
{
observation = [GSKVOObservation new];
GSAssignZeroingWeakPointer((void**)&observation->observer,
(void*)anObserver);
observation->context = aContext;
observation->options = options;
[pathInfo->observations addObject: observation];
[observation release];
pathInfo->allOptions |= options;
}
if (options & NSKeyValueObservingOptionInitial)
{
/* If the NSKeyValueObservingOptionInitial option is set,
* we must send an immediate notification containing the
* existing value in the NSKeyValueChangeNewKey
*/
[pathInfo->change setObject: [NSNumber numberWithInt: 1]
forKey: NSKeyValueChangeKindKey];
if (options & NSKeyValueObservingOptionNew)
{
id value;
value = [instance valueForKeyPath: aPath];
if (value == nil)
{
value = null;
}
[pathInfo->change setObject: value
forKey: NSKeyValueChangeNewKey];
}
[anObserver observeValueForKeyPath: aPath
ofObject: instance
change: pathInfo->change
context: aContext];
}
[iLock unlock];
}
- 判斷我們的觀察者是否能夠響應(yīng):
observeValueForKeyPath:ofObject:change:context:
方法。常規(guī)操作俩块,沒有回調(diào)黎休,響應(yīng)就沒有什么意義了! - 通過獲取
pathInfo
來保存KVO信息
- 中間對
context
&options
的處理數(shù)據(jù) -
NSKeyValueObservingOptionInitial
就會主動發(fā)起一次KVO
響應(yīng):observeValueForKeyPath
觀察屬性變化的時候
- (void) willChangeValueForKey: (NSString*)aKey
{
GSKVOPathInfo *pathInfo;
GSKVOInfo *info;
info = (GSKVOInfo *)[self observationInfo];
if (info == nil)
{
return;
}
pathInfo = [info lockReturningPathInfoForKey: aKey];
if (pathInfo != nil)
{
if (pathInfo->recursion++ == 0)
{
id old = [pathInfo->change objectForKey: NSKeyValueChangeNewKey];
if (old != nil)
{
/* We have set a value for this key already, so the value
* we set must now be the old value and we don't need to
* refetch it.
*/
[pathInfo->change setObject: old
forKey: NSKeyValueChangeOldKey];
[pathInfo->change removeObjectForKey: NSKeyValueChangeNewKey];
}
else if (pathInfo->allOptions & NSKeyValueObservingOptionOld)
{
/* We don't have an old value set, so we must fetch the
* existing value because at least one observation wants it.
*/
old = [self valueForKey: aKey];
if (old == nil)
{
old = null;
}
[pathInfo->change setObject: old
forKey: NSKeyValueChangeOldKey];
}
[pathInfo->change setValue:
[NSNumber numberWithInt: NSKeyValueChangeSetting]
forKey: NSKeyValueChangeKindKey];
[pathInfo notifyForKey: aKey ofInstance: [info instance] prior: YES];
}
[info unlock];
}
[self willChangeValueForDependentsOfKey: aKey];
}
- 通過
pathInfo
獲取回之前的舊值 -
pathInfo->change
里面的數(shù)據(jù)處理 - 重點:
[pathInfo notifyForKey: aKey ofInstance: [info instance] prior: YES];
開始發(fā)起響應(yīng)通知
- (void) notifyForKey: (NSString *)aKey ofInstance: (id)instance prior: (BOOL)f
{
unsigned count;
id oldValue;
id newValue;
if (f == YES)
{
if ((allOptions & NSKeyValueObservingOptionPrior) == 0)
{
return; // Nothing to do.
}
[change setObject: [NSNumber numberWithBool: YES]
forKey: NSKeyValueChangeNotificationIsPriorKey];
}
else
{
[change removeObjectForKey: NSKeyValueChangeNotificationIsPriorKey];
}
oldValue = [[change objectForKey: NSKeyValueChangeOldKey] retain];
if (oldValue == nil)
{
oldValue = null;
}
newValue = [[change objectForKey: NSKeyValueChangeNewKey] retain];
if (newValue == nil)
{
newValue = null;
}
/* Retain self so that we won't be deallocated during the
* notification process.
*/
[self retain];
count = [observations count];
while (count-- > 0)
{
GSKVOObservation *o = [observations objectAtIndex: count];
if (f == YES)
{
if ((o->options & NSKeyValueObservingOptionPrior) == 0)
{
continue;
}
}
else
{
if (o->options & NSKeyValueObservingOptionNew)
{
[change setObject: newValue
forKey: NSKeyValueChangeNewKey];
}
}
if (o->options & NSKeyValueObservingOptionOld)
{
[change setObject: oldValue
forKey: NSKeyValueChangeOldKey];
}
[o->observer observeValueForKeyPath: aKey
ofObject: instance
change: change
context: o->context];
}
[change setObject: oldValue forKey: NSKeyValueChangeOldKey];
[oldValue release];
[change setObject: newValue forKey: NSKeyValueChangeNewKey];
[newValue release];
[self release];
}
- change里面值的處理完畢之后
- 讓我們的觀察者響應(yīng)實現(xiàn)的KVO回調(diào)方法:
[o->observer observeValueForKeyPath: aKey ofObject: instance change: change context: o->context];
- 完美看到響應(yīng)回調(diào)玉凯,舒服
移除觀察者
移除觀察的流程相對來說势腮,比較簡單了,但是優(yōu)秀的我還是愿意和大家一起探索
- (void) removeObserver: (NSObject*)anObserver forKeyPath: (NSString*)aPath
{
GSKVOInfo *info;
id forwarder;
/*
* Get the observation information and remove this observation.
*/
info = (GSKVOInfo*)[self observationInfo];
forwarder = [info contextForObserver: anObserver ofKeyPath: aPath];
[info removeObserver: anObserver forKeyPath: aPath];
if ([info isUnobserved] == YES)
{
/*
* The instance is no longer being observed ... so we can
* turn off key-value-observing for it.
*/
object_setClass(self, [self class]);
IF_NO_GC(AUTORELEASE(info);)
[self setObservationInfo: nil];
}
if ([aPath rangeOfString:@"."].location != NSNotFound)
[forwarder finalize];
}
- 拿回我們
observationInfo
就是我們信息收集者 - 利用
NSMapRemove(paths, (void*)aPath)
移除 - 動態(tài)子類的
isa
和原類的isa
切換回來 - 把當前設(shè)置的
info
置空
OK 完美解析了KVO底層源碼捎拯!我們在探索完KVO底層實現(xiàn)才能說是真正的掌握了,而不是通過面試寶典背下結(jié)論盲厌,那是沒有什么意義! 在真正的高手對決間一眼就能看出署照,中間忽略了一些小細節(jié),比如set的多種情況吗浩,
setNumber
類型建芙,setInt
類型,setLong
類型....我相信聰明的你一樣可以解析讀懂!
對于以上技術(shù)點懂扼,想要更好的探討禁荸,可以進入iOS技術(shù)圈右蒲,一起探討學習