RxSwift(8)—— KVO底層探索(上)

就問此時(shí)此刻還有誰?45度仰望天空,該死!我這無處安放的魅力!


RxSwift目錄直通車--- 和諧學(xué)習(xí),不急不躁!


KVO在我們實(shí)際開發(fā)之中運(yùn)用非常之多,很多開發(fā)者都知道原理!但是這些原理是如何來的,一般都是淺嘗輒止。這個(gè)篇章我會(huì)從 Swift 入手分析,探索KVO底層源碼.希望讓讀者真正掌握這一塊底層,知其然而知其所以然!

KVO簡(jiǎn)介

首先我們從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")

其實(shí)我們也知道,就是平時(shí)在開發(fā)的時(shí)候,我們也可以通過計(jì)算型屬性也可以直接觀察

var name: String = ""{
    willSet{
        print(newValue)
    }
    didSet{
        print(oldValue)
    }
}

問題來了:這兩者有什么關(guān)系?

KVO與計(jì)算型屬性的關(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)
}
  • willChangeValuedidChangeValue 作為數(shù)據(jù)改變的兩個(gè)重要的方法
  • 我們通過這兩個(gè)方法繼續(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
  • 實(shí)現(xiàn)了 NSKeyValueObservingCustomization 的協(xié)議
public protocol NSKeyValueObservingCustomization : NSObjectProtocol {
    static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath>
    static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool
}
  • 這也是我們兩個(gè)非常重要的方法,平時(shí)在開發(fā)也是很有利的方法,keyPathsAffectingValue能夠建立 keyPath 的依賴,例如兩個(gè)屬性的變化同時(shí)影響一個(gè)重要屬性的改變:進(jìn)度 = 下載量 / 總量
  • automaticallyNotifiesObservers 自動(dòng)開關(guān)
  • 很明顯我們的計(jì)算型屬性在willSet里面就調(diào)用willChangeValue,didSet調(diào)用didChangeValue,的確我們計(jì)算型屬性是和我們KVO相關(guān)方法是有所關(guān)聯(lián),這里也直接證明!
  • OK,我們探索完這個(gè)問題,我們摸著這條線繼續(xù)探索KVO底層!

KVO底層

這里說明一下,本篇章的貼出的源碼沒有給大家省略,目的是想讓大家認(rèn)真閱讀,自己對(duì)照學(xué)習(xí)。當(dāng)然可能中間我也忽略過一些細(xì)節(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)建了一個(gè)動(dòng)態(tài)子類名字:"NSKVONotifing_原類的名字"
    • 添加了class、set、dealloc方法
    • 原類的isa與動(dòng)態(tài)isa切換
  • 由原來的觀察者進(jìn)行遷移到 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信息
  • 中間對(duì)context&options的處理數(shù)據(jù)
  • NSKeyValueObservingOptionInitial就會(huì)主動(dòng)發(fā)起一次KVO響應(yīng):observeValueForKeyPath

觀察屬性變化的時(shí)候

- (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ù)處理
  • 重點(diǎn):[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)實(shí)現(xiàn)的KVO回調(diào)方法: [o->observer observeValueForKeyPath: aKey ofObject: instance change: change context: o->context];
  • 完美看到響應(yīng)回調(diào),舒服

移除觀察者

移除觀察的流程相對(duì)來說,比較簡(jiǎn)單了,但是優(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)移除
  • 動(dòng)態(tài)子類的isa和原類的isa切換回來
  • 把當(dāng)前設(shè)置的info置空

OK 完美解析了KVO底層源碼!我們?cè)谔剿魍闗VO底層實(shí)現(xiàn)才能說是真正的掌握了,而不是通過面試寶典背下結(jié)論,那是沒有什么意義! 在真正的高手對(duì)決間一眼就能看出,中間忽略了一些小細(xì)節(jié),比如set的多種情況,setNumber類型,setInt類型, setLong類型....我相信聰明的你一樣可以解析讀懂!

就問此時(shí)此刻還有誰?45度仰望天空,該死!我這無處安放的魅力!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容