在iOS9
中調(diào)整了NSNotificatinonCenter

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