NSNotificatinonCenter iOS9以后不再需要移除觀察者-備忘

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

WechatIMG455.jpeg

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)行的。

最后編輯于
?著作權(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)容