面试好文

Notification是否是在同一个线程完成post和obse

2018-09-20  本文已影响14人  NapoleonY

问题

如果在线程A中发送通知,接收到通知后调用的方法是否是运行在线程A中?

举例

// 线程A中发送通知
NotificationCenter.default.post(name: NotifyConnectStateChanged, object: nil, userInfo: ["state":connectState])

// 在主线程中添加observer
NotificationCenter.default.addObserver(self, selector: #selector(connectedStateChanged(noti:)), name: NotifyConnectStateChanged, object: nil)

验证

  1. 在线程A中post通知
DispatchQueue.global().async {
            NotificationCenter.default.post(name: notifyNa, object: nil)
}
  1. 在ViewDidLoad中注册观察者
override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(self.notify(noti:)), name: notifyNa, object: nil)
}

此时是在主线程中注册了观察者

  1. 发送广播,观察是在注册观察者的主线程还是在发送广播的其他线程中调用selector


    结果图

    从图中可以看出,广播的发送和接收都在同一个线程中。

结果

Notification是在同一个线程完成post和observer的处理

上一篇 下一篇

猜你喜欢

热点阅读