NSNotification!對就是它涝滴,看著代碼比較惡心,后期難以維護(hù)的一種回調(diào)傳值模式——通知胶台。(不能黑它狭莱,它也是蘋果的一種常用的Api設(shè)計模式,它有它特定的使用場景概作,不再多說了,可以在AFNetWorking搜索下NSNotification默怨,很多啊讯榕,有木有)
什么?它也有多線程使用的問題存在?notification 在多線程的情況下愚屁,線程的管理非常不好控制济竹。這個怎么理解呢?
先看官方文檔的解釋:Regular notification centers deliver notifications on the thread in which the notification was posted. Distributed notification centers deliver notifications on the main thread. At times, you may require notifications to be delivered on a particular thread that is determined by you instead of the notification center. For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.
文檔意思總結(jié)來說就是:NSNotification接受線程是基于發(fā)送消息的線程的霎槐,也就是要同步啦送浊。如果你發(fā)送的消息不在主線程,接受消息就會自動在子線程中執(zhí)行(不管你在主線程或者是子線程中注冊消息)丘跌。那怎么辦袭景?在你收到消息通知的時候,注意選擇你要執(zhí)行的線程闭树。如果在子線程中發(fā)送消息耸棒,則需要重定向到主線程中執(zhí)行任務(wù)(比如刷新UI)。
話不多說报辱,上代碼与殃。
在子線程中執(zhí)行消息的情況。
看打印幅疼,testNotify通知執(zhí)行由于受在子線程中發(fā)通知的影響,也在子線程中執(zhí)行昼接。
怎么辦爽篷?
1.先說一個比較low的辦法,在sendNotify函數(shù)中強(qiáng)制切到主線程辩棒,代碼省略狼忱,大家應(yīng)該都懂得。缺陷是每一個響應(yīng)函數(shù)都強(qiáng)制切換線程一睁。這樣帶來的問題就是每一處理響應(yīng)通知的代碼你都得這樣做钻弄,對于開發(fā)者而言負(fù)擔(dān)太大。
2.從定向到主線程執(zhí)行者吁。
apple 從 iOS4 之后提供了帶有 block 的 NSNotification窘俺。使用方式如下:
-(id)addObserverForName:(NSString*)nameobject:(id)objqueue:(NSOperationQueue*)queue
此時,看打印
我們通過這個采用block執(zhí)行通知的新的注冊通知的方法瘤泪,只要設(shè)置[NSOperationQueuemainQueue],輕松實現(xiàn)在主線程中執(zhí)行任務(wù)育八,so easy对途!大家可以大膽用起來。