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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值