在iOS9
中調整了NSNotificatinonCenter
iOS9
開始不需要在觀察者對象釋放之前從通知中心移除觀察者了。但是如果使用-[NSNotificationCenter addObserverForName:object:queue:usingBlock:]
方法還是需要手動釋放。因為NSNotificationCenter
依舊對它們強引用。# NSNotificationQueueNSNotificationQueue
通知隊列,用來管理多個通知的調用。通知隊列通常以先進先出(FIFO)順序維護通。NSNotificationQueue
就像一個緩沖池把一個個通知放進池子中,使用特定方式通過NSNotificationCenter
發送到相應的觀察者。下面我們會提到特定的方式即合并通知和異步通知。
創建通知隊列方法:- (instancetype)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter NS_DESIGNATED_INITIALIZER;
往隊列加入通知方法:- (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;
發送方式NSPostingStyle
包括三種類型:typedef NS_ENUM(NSUInteger, NSPostingStyle) {NSPostWhenIdle = 1,NSPostASAP = 2,NSPostNow = 3};
NSPostWhenIdle:空閑發送通知 當運行循環處于等待或空閑狀態時,發送通知,對于不重要的通知可以使用。NSPostASAP:盡快發送通知 當前運行循環迭代完成時,通知將會被發送,有點類似沒有延遲的定時器。NSPostNow :同步發送通知 如果不使用合并通知 和postNotification:
一樣是同步通知。
合并通知NSNotificationCoalescing
也包括三種類型:typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {NSNotificationNoCoalescing = 0,NSNotificationCoalescingOnName = 1,NSNotificationCoalescingOnSender = 2};
NSNotificationNoCoalescing:不合并通知。NSNotificationCoalescingOnName:合并相同名稱的通知。NSNotificationCoalescingOnSender:合并相同通知和同一對象的通知。
通過合并我們可以用來保證相同的通知只被發送一次。forModes:(nullable NSArray<NSRunLoopMode> *)modes
可以使用不同的NSRunLoopMode
配合來發送通知,可以看出實際上NSNotificationQueue
與RunLoop
的機制以及運行循環有關系,通過NSNotificationQueue
隊列來發送的通知和關聯的RunLoop
運行機制來進行的。