NSNotificationCenter是否按观察者添加顺序分发通知?
确认NSNotificationCenter观察者调用顺序的官方依据
咱们先还原下你的测试场景,再说说哪里能找到官方确认依据:
你在全局后台队列中批量添加了多个监听UIApplicationDidEnterBackgroundNotification的观察者,代码如下:
dispatch_async(dispatch_get_global_queue(0, 0), ^{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method1) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method2) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method3) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method4) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method5) name:UIApplicationDidEnterBackgroundNotification object:nil]; });
测试发现当App进入后台时,方法严格按照添加顺序执行:
[method1 called] [method2 called] [method3 called] [method4 called] [method5 called]
哪里能确认“先添加先收到通知”的规则?
你可以在两个官方渠道找到明确的说明:
- NSNotificationCenter类参考文档:查看
postNotificationName:object:userInfo:方法的详细说明,里面明确标注:通知会按照观察者注册的先后顺序分发给各个观察者。 - Apple的Notifications Programming Topics:在“Notification Delivery Order”相关章节中,也清晰指出了观察者接收通知的顺序与注册顺序完全一致。
另外补充个小细节:你这里是在同一个代码块里串行执行添加操作(虽然用了全局并发队列,但单个block内的代码是串行执行的),所以注册顺序是完全可控的;如果是在不同线程并发添加观察者,那注册顺序可能会不确定,但一旦注册完成,后续通知的分发顺序就固定为最终的注册先后顺序了。
内容的提问来源于stack exchange,提问作者waitianlou
相关产品推荐
相关产品推荐

