Notification與多線程

一個NSNotificationCenter對象(通知中心)提供了在程序中廣播消息的機制,它實質上就是一個通知分發表。這個分發表負責維護爲各個通知註冊的觀察者,並在通知到達時,去查找相應的觀察者,將通知轉發給他們進行處理。html

[原文:An NSNotificationCenter object (or simply, notification center) provides a mechanism for broadcasting information within a program. An NSNotificationCenter object is essentially a notification dispatch table.]ios

調試融雲IM消息接收器回調方法時,碰到一些問題,下面將一一指出。app

code:異步

// 消息接收器(聊天室功能中,A客戶端發送消息,B客戶端可在該方法中回調消息)
- (void)onReceived:(RCMessage *)message
              left:(int)nLeft
            object:(id)object {
      DLog(@"Thread = %@", [NSThread currentThread]);
}    

Log:async

<BDChatRoomBaseController.m : -[BDChatRoomBaseController onReceived:left:object:] : 193> ——> Thread = <NSThread: 0x7fb7e2d6a340>{number = 4, name = (null)}

結論:當A客戶端發送消息時,B客戶端回調該方法是在子線程中異步回調的聊天結果。此時我想在此處發送消息接收的通知,做爲他用!ide

代碼爲:post

- (void)onReceived:(RCMessage *)message left:(int)nLeft object:(id)object {
    DLog(@"Thread = %@", [NSThread currentThread]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TESTMESSAGE_NOTIFICATION" object:nil];
}

在控制器聲明週期方法 viewDidLoad 中註冊該通知。ui

code:spa

#pragma mark - View lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // 註冊通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:@"TESTMESSAGE_NOTIFICATION" object:nil];
}

// 通知響應方法
- (void)receiveMessage:(NSNotification *)notification {
    DLog(@"Thread = %@", [NSThread currentThread]);
    DLog(@"userInfo = %@", notification.userInfo);
}

Log:線程

<BDConversationController.m : -[BDConversationController receiveMessage:] : 27> ——> Thread = <NSThread: 0x7feb35859d60>{number = 9, name = (null)}
<BDConversationController.m : -[BDConversationController receiveMessage:] : 28> ——> userInfo = (null)

結論:能夠發現,子線程發出的通知,就會在子線程處理通知。

注意:在 - (void)receiveMessage:(NSNotification *)notification 刷新UI時,咱們須要考慮到回到主線程刷新頁面(線程通訊)。

code:

// 通知響應方法
- (void)receiveMessage:(NSNotification *)notification {
    DLog(@"Thread = %@", [NSThread currentThread]);
    DLog(@"userInfo = %@", notification.userInfo);
    dispatch_async(dispatch_get_main_queue(), ^{
        // 刷新UI
    });
}

就能夠成功的刷新UI了。

參考文檔:

NSNotificationCenter Class Reference

尊重做者勞動成果,轉載請註明: 【kingdev】

相關文章
相關標籤/搜索