Notification与多线程

一个NSNotificationCenter对象(通知中心)提供了在程序中广播消息的机制,它实质上就是一个通知分发表。这个分发表负责维护为各个通知注册的观察者,并在通知到达时,去查找相应的观察者,将通知转发给他们进行处理。

[原文: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.]

调试融云IM消息接收器回调方法时,碰到一些问题,下面将一一指出。

code:

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

Log:

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

结论:当A客户端发送消息时,B客户端回调该方法是在子线程中异步回调的聊天结果。此时我想在此处发送消息接收的通知,作为他用!

代码为:

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

在控制器声明周期方法 viewDidLoad 中注册该通知。

code:

#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】

原文地址:https://www.cnblogs.com/xiu619544553/p/5437788.html