iOS:通知

關鍵類

NSNotification

用于描述通知的類,一個NSNotification對象就包含了一條通知的信息。

// 通知名稱
@property (readonly, copy) NSNotificationName name;
// 通知攜帶的對象
@property (nullable, readonly, retain) id object;
// 發(fā)送通知時 配置的信息
@property (nullable, readonly, copy) NSDictionary *userInfo;

// 初始化方法
- (instancetype)initWithName:(NSNotificationName)name object:(nullable id)object userInfo:(nullable NSDictionary *)userInfo;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

NSNotificationCenter

是個單例類,負責管理通知的創(chuàng)建和發(fā)送,屬于最核心的類了。它主要做三件事:
1、添加通知
2、發(fā)送通知
3、移除通知

// 全局唯一NSNotificationCenter對象
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;

// 在通知中心添加一個通知
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;

// 發(fā)出一個通知
- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

// 移除一個通知
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;

// 添加一個通知觀察者,并在收到指定通知時執(zhí)行指定的代碼塊
// 指定代碼塊的操作隊列。如果為 nil,則在發(fā)送通知的線程上執(zhí)行代碼塊。
// 返回的觀察者對象 用于移除時使用
- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (NS_SWIFT_SENDABLE ^)(NSNotification *note))block ;

注意:
1、添加通知時observer和sel都不可為空,通知名稱name和攜帶對象object可以為空。
2、注冊通知時應避免重復注冊,會導致重復處理通知信息
3、使用block時,block內可能會持有外部對象,避免循環(huán)引用。
4、消息發(fā)送類型需要和注冊時一致。
若注冊時同時指定了名稱和攜帶對象,發(fā)到那個消息時也要指定,否則無法收到消息(更多原因會在底層分析時介紹)
5、移除通知,ios9及macos10.11之后不需要手動調用,dealloc已經(jīng)自動處理。

NSNotificationQueue

通知隊列,用于異步發(fā)送消息。
這個異步并不是開啟線程,而是把通知存到雙向鏈表實現(xiàn)的隊列里面,
等待某個時機觸發(fā)時調用NSNotificationCenter的發(fā)送接口進行發(fā)送通知。
NSNotificationQueue最終還是調用NSNotificationCenter進行消息的分發(fā)。

NSNotificationQueue主要做了兩件事:
1、添加通知到隊列
2、刪除通知

// 獲取當前當前線程綁定的通知消息隊列
@property (class, readonly, strong) NSNotificationQueue *defaultQueue;
// 指定通知中心創(chuàng)建通知隊列
- (instancetype)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter ;

// 把通知添加到隊列中
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle;
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle coalesceMask:(NSNotificationCoalescing)coalesceMask forModes:(nullable NSArray<NSRunLoopMode> *)modes;

// 刪除通知,把滿足合并條件的通知從隊列中刪除
- (void)dequeueNotificationsMatching:(NSNotification *)notification coalesceMask:(NSUInteger)coalesceMask;

通知的發(fā)送時機

typedef NS_ENUM(NSUInteger, NSPostingStyle) {
    NSPostWhenIdle = 1, // runloop空閑時發(fā)送通知
    NSPostASAP = 2,     // 當前通知調用或者計時器結束發(fā)出通知
    NSPostNow = 3       // 立刻發(fā)送或在合并通知完成之后發(fā)送
};

通知的合并策略

// 有些時候同名通知只想存在一個,這時候就可以用到它了
typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {
    NSNotificationNoCoalescing = 0,// 默認不合并
    NSNotificationCoalescingOnName = 1,// 按照通知name合并,相同就合并
    NSNotificationCoalescingOnSender = 2// 按照傳入的object合并,相同就合并
};

底層分析

由于蘋果沒有對相關源碼開放,所以以GNUStep源碼為基礎進行研究,雖然GNUStep不是蘋果官方的源碼,但很具有參考意義,根據(jù)實現(xiàn)原理來猜測和實踐,更重要的還可以學習觀察者模式的架構設計。

1、_GSIMapTable

 *  A rough picture is include below:
 *   
 *  
 *   This is the map                C - array of the buckets
 *   +---------------+             +---------------+
 *   | _GSIMapTable  |      /----->| nodeCount     |  
 *   |---------------|     /       | firstNode ----+--\  
 *   | buckets    ---+----/        | ..........    |  |
 *   | bucketCount  =| size of --> | nodeCount     |  |
 *   | nodeChunks ---+--\          | firstNode     |  |
 *   | chunkCount  =-+\ |          |     .         |  | 
 *   |   ....        || |          |     .         |  |
 *   +---------------+| |          | nodeCount     |  |
 *                    | |          | fistNode      |  | 
 *                    / |          +---------------+  | 
 *         ----------   v                             v
 *       /       +----------+      +---------------------------+ 
 *       |       |  * ------+----->| Node1 | Node2 | Node3 ... | a chunk
 *   chunkCount  |  * ------+--\   +---------------------------+
 *  is size of = |  .       |   \  +-------------------------------+
 *               |  .       |    ->| Node n | Node n + 1 | ...     | another
 *               +----------+      +-------------------------------+
 *               array pointing
 *               to the chunks
 *
#if !defined(GSI_MAP_TABLE_T)
typedef struct _GSIMapBucket GSIMapBucket_t;
typedef struct _GSIMapNode GSIMapNode_t;

typedef GSIMapBucket_t *GSIMapBucket;
typedef GSIMapNode_t *GSIMapNode;
#endif

struct  _GSIMapNode {
  GSIMapNode    nextInBucket;   /* Linked list of bucket.   */
  GSIMapKey key;
#if GSI_MAP_HAS_VALUE
  GSIMapVal value;
#endif
};

struct  _GSIMapBucket {
  uintptr_t nodeCount;  /* Number of nodes in bucket.   */
  GSIMapNode    firstNode;  /* The linked list of nodes.    */
};

#if defined(GSI_MAP_TABLE_T)
typedef GSI_MAP_TABLE_T *GSIMapTable;
#else
typedef struct _GSIMapTable GSIMapTable_t;
typedef GSIMapTable_t *GSIMapTable;

struct  _GSIMapTable {
  NSZone    *zone;
  uintptr_t nodeCount;  /* Number of used nodes in map. */
  uintptr_t bucketCount;    /* Number of buckets in map.    */
  GSIMapBucket  buckets;    /* Array of buckets.        */
  GSIMapNode    freeNodes;  /* List of unused nodes.    */
  uintptr_t chunkCount; /* Number of chunks in array.   */
  GSIMapNode    *nodeChunks;    /* Chunks of allocated memory.  */
  uintptr_t increment;
#ifdef  GSI_MAP_EXTRA
  GSI_MAP_EXTRA extra;
#endif
};

_GSIMapTable結構體內的變量理解:
1、buckets:存儲著GSIMapBucket對象的數(shù)組,可以堪稱是一個單向鏈表,每個GSIMapBucket中的firstNode->nextInBucket表示下一個bucket,依次連接。
2、bucketCount表示buckets的數(shù)量。
3、nodeChunks,表示一個數(shù)組指針,數(shù)組存儲所有單鏈表的首個元素node。
4、chunkCount 表示數(shù)組大小。
5、freeNodes是需要釋放的元素,是一個單向鏈表。
_GSIMapTable其實就是一個hash表結構,既可以以數(shù)組的形式取到每個單向鏈表首元素,也可以以鏈表形式取得。通過數(shù)組能夠方便取到每個單向鏈表,再利用鏈表結構方便增刪。

存儲容器NCTbl

// 根容器,NSNotificationCenter持有
typedef struct NCTbl {
  Observation       *wildcard;  /* 鏈表結構,保存既沒有name也沒有object的通知 */
  GSIMapTable       nameless;   /* 存儲沒有name但是有object的通知 */
  GSIMapTable       named;      /* 存儲帶有name的通知,不管有沒有object  */
    ...
} NCTable;

// Observation 存儲觀察者和響應結構體,基本的存儲單元
typedef struct  Obs {
  id        observer;   /* 觀察者,接收通知的對象  */
  SEL       selector;   /* 響應方法     */
  struct Obs    *next;      /* Next item in linked list.    */
  ...
} Observation;

wildcard:Observation結構,存儲既沒有name也沒有object的通知
nameless:GSIMapTable結構,存儲存儲沒有name但是有object的通知
named:GSIMapTable,存儲帶有name的通知,不管有沒有object的通知。

注冊通知

selector: (SEL)selector注冊通知

/*
observer:觀察者,即通知的接收者
selector:接收到通知時的響應方法
name: 通知name
object:攜帶對象
*/
- (void) addObserver: (id)observer
            selector: (SEL)selector
                name: (NSString*)name 
                object: (id)object {
  // 前置條件判斷
  ......

  // 創(chuàng)建一個observation對象,持有觀察者和SEL,下面進行的所有邏輯就是為了存儲它
  o = obsNew(TABLE, selector, observer);

/*======= case1: 如果name存在 =======*/
  if (name) {
    //-------- NAMED是個宏,表示名為named字典。以name為key,從named表中獲取對應的mapTable
      n = GSIMapNodeForKey(NAMED, (GSIMapKey)(id)name);
      if (n == 0) { // 不存在,則創(chuàng)建 
          m = mapNew(TABLE); // 先取緩存,如果緩存沒有則新建一個map
          GSIMapAddPair(NAMED, (GSIMapKey)(id)name, (GSIMapVal)(void*)m);
          ...
      }
      else { // 存在則把值取出來 賦值給m
          m = (GSIMapTable)n->value.ptr;
      }
    //-------- 以object為key,從字典m中取出對應的value,其實value被MapNode的結構包裝了一層,這里不追究細節(jié)
      n = GSIMapNodeForSimpleKey(m, (GSIMapKey)object);
      if (n == 0) {// 不存在,則創(chuàng)建 
          o->next = ENDOBS;
          GSIMapAddPair(m, (GSIMapKey)object, (GSIMapVal)o);
      }
      else {
          list = (Observation*)n->value.ptr;
          o->next = list->next;
          list->next = o;
      }
    }
/*======= case2:如果name為空,但object不為空 =======*/
  else if (object) {
    // 以object為key,從nameless字典中取出對應的value,value是個鏈表結構
      n = GSIMapNodeForSimpleKey(NAMELESS, (GSIMapKey)object);
      // 不存在則新建鏈表,并存到map中
      if (n == 0) { 
          o->next = ENDOBS;
          GSIMapAddPair(NAMELESS, (GSIMapKey)object, (GSIMapVal)o);
      }
      else { // 存在 則把值接到鏈表的節(jié)點上
        ...
      }
    }
/*======= case3:name 和 object 都為空 則存儲到wildcard鏈表中 =======*/
  else {
      o->next = WILDCARD;
      WILDCARD = o;
  }
}

從上面介紹的存儲容器中我們了解到NCTable結構體中核心的三個變量以及功能:wildcard、named、nameless,在源碼中直接用宏定義表示了:WILDCARD、NAMELESS、NAMED。

case1: 存在name(無論object是否存在)

1、注冊通知,如果通知的name存在,則以name為key從named字典中取出值n(這個n其實被MapNode包裝了一層,便于理解這里直接認為沒有包裝),這個n還是個字典,各種判空新建邏輯不討論。
2、然后以object為key,從字典n中取出對應的值,這個值就是Observation類型(后面簡稱obs)的鏈表,然后把剛開始創(chuàng)建的obs對象o存儲進去。

數(shù)據(jù)結構關系圖

如果注冊通知時傳入name,那么會是一個雙層的存儲結構
1、找到NCTable中的named表,這個表存儲了還有name的通知
2、以name作為key,找到value,這個value依然是一個map
3、map的結構是以object作為key,obs對象為value,這個obs對象的結構上面已經(jīng)解釋,主要存儲了observer & SEL

case2: 只存在object

1、以object為key,從nameless字典中取出value,此value是個obs類型的鏈表。
2、把創(chuàng)建的obs類型的對象o存儲到鏈表中。

數(shù)據(jù)結構關系圖

只存在object時存儲只有一層,那就是object和obs對象之間的映射

case3: 沒有name和object

這種情況直接把obs對象存放在了Observation *wildcard 鏈表結構中。

block - 注冊通知

- (id) addObserverForName: (NSString *)name 
                   object: (id)object 
                    queue: (NSOperationQueue *)queue 
               usingBlock: (GSNotificationBlock)block
{
    // 創(chuàng)建一個臨時觀察者
    GSNotificationObserver *observer = 
        [[GSNotificationObserver alloc] initWithQueue: queue block: block];
    // 調用了@selector的注冊方法
    [self addObserver: observer 
             selector: @selector(didReceiveNotification:) 
                 name: name 
               object: object];

    return observer;
}

- (void) didReceiveNotification: (NSNotification *)notif {
    if (_queue != nil) {
        GSNotificationBlockOperation *op = [[GSNotificationBlockOperation alloc] 
            initWithNotification: notif block: _block];
        [_queue addOperation: op];
    } else {
        CALL_BLOCK(_block, notif);
    }
}

這個接口依賴于selector注冊,,只是多了一層代理觀察者GSNotificationObserver,
1、創(chuàng)建一個GSNotificationObserver類型的對象observer,并把queue和block保存下來
2、調用接口1進行通知的注冊
3、接收到通知時會響應observer的didReceiveNotification:方法,然后在didReceiveNotification:中把block拋給指定的queue去執(zhí)行。

從上述介紹可以總結:
1、存儲是以name和object為維度的,即判定是不是同一個通知要從name和object區(qū)分,如果他們都相同則認為是同一個通知,后面包括查找邏輯、刪除邏輯都是以這兩個為維度的,問題列表中的第九題也迎刃而解了。
2、理解數(shù)據(jù)結構的設計是整個通知機制的核心,其他功能只是在此基礎上擴展了一些邏輯。
3、存儲過程并沒有做去重操作,這也解釋了為什么同一個通知注冊多次則響應多次。

發(fā)送通知

// 發(fā)送通知
- (void) postNotificationName: (NSString*)name
               object: (id)object
             userInfo: (NSDictionary*)info
{
// 構造一個GSNotification對象, GSNotification繼承了NSNotification
  GSNotification    *notification;
  notification = (id)NSAllocateObject(concrete, 0, NSDefaultMallocZone());
  notification->_name = [name copyWithZone: [self zone]];
  notification->_object = [object retain];
  notification->_info = [info retain];

  // 進行發(fā)送操作
  [self _postAndRelease: notification];
}
//發(fā)送通知的核心函數(shù),主要做了三件事:查找通知、發(fā)送、釋放資源
- (void) _postAndRelease: (NSNotification*)notification {
    //step1: 從named、nameless、wildcard表中查找對應的通知
    ...
    //step2:執(zhí)行發(fā)送,即調用performSelector執(zhí)行響應方法,從這里可以看出是同步的
    [o->observer performSelector: o->selector
                    withObject: notification];
    //step3: 釋放資源
    RELEASE(notification);
}

上述代碼注釋說的很清晰了,主要做了三件事
1、通過name & object 查找到所有的obs對象(保存了observer和sel),放到數(shù)組中。
2、通過performSelector:逐一調用sel,這是個同步操作。
3、釋放notification對象。

發(fā)送過程的概述:
1、從三個存儲容器中:named、nameless、wildcard去查找對應的obs對象。
2、然后通過performSelector:逐一調用響應方法,這就完成了發(fā)送流程。

核心點:
1、同步發(fā)送
2、遍歷所有列表,即注冊多次通知就會響應多次

刪除通知

1、查找時仍然以name和object為維度的,再加上observer做區(qū)分。
2、因為查找時做了這個鏈表的遍歷,所以刪除時會把重復的通知全都刪除掉。

更多源碼下載GNUStep

異步通知

入隊

入隊
下面為精簡版的源碼,看源碼的注釋,基本上能明白大致邏輯
1、根據(jù)coalesceMask參數(shù)判斷是否合并通知。
2、接著根據(jù)postingStyle參數(shù),判斷通知發(fā)送的時機,
如果不是立即發(fā)送則把通知加入到隊列中:_asapQueue、_idleQueue。

核心點:
1、隊列是雙向鏈表實現(xiàn)
2、當postingStyle值是立即發(fā)送時,調用的是NSNotificationCenter進行發(fā)送的,所以NSNotificationQueue還是依賴NSNotificationCenter進行發(fā)送

/*
* 把要發(fā)送的通知添加到隊列,等待發(fā)送
* NSPostingStyle 和 coalesceMask在上面的類結構中有介紹
* modes這個就和runloop有關了,指的是runloop的mode
*/ 
- (void) enqueueNotification: (NSNotification*)notification
        postingStyle: (NSPostingStyle)postingStyle
        coalesceMask: (NSUInteger)coalesceMask
            forModes: (NSArray*)modes
{
    ......
  // 判斷是否需要合并通知
  if (coalesceMask != NSNotificationNoCoalescing) {
      [self dequeueNotificationsMatching: notification
                coalesceMask: coalesceMask];
  }
  switch (postingStyle) {
      case NSPostNow: {
        ...
        // 如果是立馬發(fā)送,則調用NSNotificationCenter進行發(fā)送
         [_center postNotification: notification];
         break;
      }
      case NSPostASAP:
        // 添加到_asapQueue隊列,等待發(fā)送
        add_to_queue(_asapQueue, notification, modes, _zone);
        break;

      case NSPostWhenIdle:
        // 添加到_idleQueue隊列,等待發(fā)送
        add_to_queue(_idleQueue, notification, modes, _zone);
        break;
    }
}

發(fā)送通知

這里截取了發(fā)送通知的核心代碼,這個發(fā)送通知邏輯如下:
1、runloop觸發(fā)某個時機,調用GSPrivateNotifyASAP()和GSPrivateNotifyIdle()方法,這兩個方法最終都調用了notify()方法。
2、notify()所做的事情就是調用NSNotificationCenter的postNotification:進行發(fā)送通知。

static void notify(NSNotificationCenter *center, 
                   NSNotificationQueueList *list,
                   NSString *mode, NSZone *zone)
{
    ......
    // 循環(huán)遍歷發(fā)送通知
    for (pos = 0; pos < len; pos++)
    {
      NSNotification    *n = (NSNotification*)ptr[pos];

      [center postNotification: n];
      RELEASE(n);
    }
    ......  
}
// 發(fā)送_asapQueue中的通知
void GSPrivateNotifyASAP(NSString *mode)
{
    notify(item->queue->_center,
        item->queue->_asapQueue,
        mode,
        item->queue->_zone);
}
// 發(fā)送_idleQueue中的通知
void GSPrivateNotifyIdle(NSString *mode)
{
    notify(item->queue->_center,
        item->queue->_idleQueue,
        mode,
        item->queue->_zone);
}

NSNotificationQueue總結:
1、依賴runloop,所以如果在其他子線程使用NSNotificationQueue,需要開啟runloop。
2、最終還是通過NSNotificationCenter進行發(fā)送通知,所以這個角度講它還是同步的。
3、所謂異步,指的是非實時發(fā)送而是在合適的時機發(fā)送,并沒有開啟異步線程。

主線程響應通知

異步線程發(fā)送通知則響應函數(shù)也是在異步線程,如果執(zhí)行UI刷新相關的話就會出問題,那么如何保證在主線程響應通知呢?
其實也是比較常見的問題了,基本上解決方式如下幾種:
1、使用addObserverForName: object: queue: usingBlock方法注冊通知,指定在mainqueue上響應block。
2、在主線程注冊一個machPort,它是用來做線程通信的,當在異步線程收到通知,然后給machPort發(fā)送消息,這樣肯定是在主線程處理的。

問題列表

1、通知的實現(xiàn)原理(結構設計、通知如何存儲的、name&observer&SEL之間的關系等)

通知里面主要有三個類NSNotification通知對象,包括name,object,userinfo
NSNotificationCenter,通知中心,負責添加、發(fā)送、移除通知。
NSNotificationQueue,通知隊列,負責某些時機觸發(fā)調用通知,最后調用還是NSNotificationCenter通知中心 post通知。
通知隊列里的異步,實際上不是真正的異步,更多是延時發(fā)送,利用了runloop的時機來觸發(fā)。

根據(jù)開源代碼GNUStep推測,通知時結構體,通過雙向鏈表進行數(shù)據(jù)存儲

// 根容器,NSNotificationCenter持有
typedef struct NCTbl {
  Observation       *wildcard;  /* 鏈表結構,保存既沒有name也沒有object的通知 */
  GSIMapTable       nameless;   /* 存儲沒有name但是有object的通知 */
  GSIMapTable       named;      /* 存儲帶有name的通知,不管有沒有object  */
    ...
} NCTable;

// Observation 存儲觀察者和響應結構體,基本的存儲單元
typedef struct  Obs {
  id        observer;   /* 觀察者,接收通知的對象  */
  SEL       selector;   /* 響應方法     */
  struct Obs    *next;      /* Next item in linked list.    */
  ...
} Observation;

通知是以key value的形式存儲,
需要重點強調:
通知以 name和object兩個緯度來存儲相關通知內容,也就是我們添加通知的時候傳入的兩個不同的方法.
name&observer&SEL之間的關系:name作為key, observer作為觀察者對象,當合適時機觸發(fā)就會調用observer的SEL

2、通知的發(fā)送時同步的,還是異步的

同步發(fā)送,因為要調用消息轉發(fā).
所謂異步,指的是非實時發(fā)送而是在合適的時機發(fā)送,并沒有開啟異步線程.

3、NSNotificationCenter 接受消息和發(fā)送消息是在一個線程里嗎?如何異步發(fā)送消息

是的, 異步線程發(fā)送通知則響應函數(shù)也是在異步線程.
異步發(fā)送通知可以開啟異步線程發(fā)送即可.

4、NSNotificationQueue是異步還是同步發(fā)送?在哪個線程響應?

// 表示通知的發(fā)送時機
typedef NS_ENUM(NSUInteger, NSPostingStyle) {
    NSPostWhenIdle = 1, // runloop空閑時發(fā)送通知
    NSPostASAP = 2, // 盡快發(fā)送,這種時機是穿插在每次事件完成期間來做的
    NSPostNow = 3 // 立刻發(fā)送或者合并通知完成之后發(fā)送
};

NSPostWhenIdle:異步發(fā)送
NSPostASAP:異步發(fā)送
NSPostNow:同步發(fā)送

NSNotificationCenter都是同步發(fā)送的,
而關于NSNotificationQueue的異步發(fā)送,從線程的角度看并不是真正的異步發(fā)送,或可稱為延時發(fā)送,它是利用了runloop的時機來觸發(fā)的。
異步線程發(fā)送通知則響應函數(shù)也是在異步線程,主線程發(fā)送則在主線程。

5、NSNotificationQueue和runloop的關系

NSNotificationQueue依賴runloop. 因為通知隊列要在runloop回調的某個時機調用通知中心發(fā)送通知。

6、如何保證通知接收的線程在主線程

兩種方式:
1、系統(tǒng)接受通知的API指定隊列
2、NSMachPort的方式 通過在主線程的 runloop 中添加 machPort,設置這個 port 的 delegate,通過這個 Port 其他線程可以跟主線程通信,在這個 port 的代理回調中執(zhí)行的代碼肯定在主線程中運行,所以,在這里調用 NSNotificationCenter 發(fā)送通知即可

7、頁面銷毀時不移除通知會崩潰嗎?

iOS9.0之前,會crash,原因:通知中心對觀察者的引用是 unsafe_unretained,導致當觀察者釋放的時候,觀察者的指針值并不為nil,出現(xiàn)野指針.
iOS9.0之后,不會crash,原因:通知中心對觀察者的引用是 weak。

8、多次添加同一個通知會是什么結果?多次移除通知呢

多次添加同一個通知,會導致發(fā)送一次這個通知的時候,響應多次通知回調。
多次移除通知不會產(chǎn)生crash。

9、下面的方式能接收到通知嗎?為什么

// 發(fā)送通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"TestNotification" object:@1];
// 接收通知
[NSNotificationCenter.defaultCenter postNotificationName:@"TestNotification" object:nil];

不能。根據(jù)推測的通知中心存儲通知觀察者的結構。

// 根容器,NSNotificationCenter持有
typedef struct NCTbl {
  Observation  *wildcard;    /* 鏈表結構,保存既沒有name也沒有object的通知 */
  GSIMapTable nameless;    /* 存儲沒有name但是有object的通知    */
  GSIMapTable named;        /* 存儲帶有name的通知,不管有沒有object    */
    ...
} NCTable;

當添加通知監(jiān)聽的時候,我們傳入了name和object,所以,觀察者的存儲鏈表是這樣的:named表:key(name) : value->key(object) : value(Observation)
因此在發(fā)送通知的時候,如果只傳入name而并沒有傳入object,是找不到Observation的,也就不能執(zhí)行觀察者回調。

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容