1.同步:
Using the NSNotificationCenter’s postNotification:` method and its variants, you can post a notification to a notification center. However, the invocation of the method is synchronous: before the posting object can resume its thread of execution, it must wait until the notification center dispatches the notification to all observers and returns.
使用NSNotificationCenter的postNotification:方法和它的变体,可以发布一个通知到通知中心。但是,该方法的调用是同步的:在发布对象可以恢复其执行线程之前,它必须等待通知中心将通知分派给所有观察者并返回。
举个例子:
两个类,Post和Observer。
Post类实现一个方法postNotification,方法中异步调用post方法发送通知。
Observer类注册两个观察者,方式1是target-action模式,不改变回调线程,
方式2是block模式,创建匿名对象作为观察者,回调到主线程,方法中都调用了sleep休眠2秒,模拟复杂操作。
代码如下:
class Observer {
func add() {
print("\n addObserver -- \(Thread.current)")
let center = NotificationCenter.default
// 方式1.
center.addObserver(self,
selector: #selector(doSomething),
name: NSNotification.Name(rawValue: theName),
object: nil)
// 方式2.
var token: NSObjectProtocol?
token = center.addObserver(forName: NSNotification.Name(rawValue: theName),
object: nil,
queue: OperationQueue.main) {_ in //主线程
print("\n 2.received -- \(Thread.current)")
sleep(2)
center.removeObserver(token!)
}
}
@objc func doSomething() {//不改变线程
print("\n 1.received -- \(Thread.current)")
sleep(2)
}
deinit {
print("\n \(self) -- deinit")
}
}
class Post {
var obj = Observer()
init() {
obj.add()
self.postNotification()
}
func postNotification() {
DispatchQueue.global().async { // 开启新线程
Thread.current.name = "com.dailyiOS"
print("\n post -- \(Thread.current)") //开始发送
let notf = Notification(name: Notification.Name(rawValue: theName))
NotificationCenter.default.post(name: notf.name, object: nil)//发送
print("\n post end -- \(Thread.current)") //发送结束
}
}
deinit {
print("\n \(self) -- deinit")
}
}
执行结果:
![](https://img.haomeiwen.com/i1926707/7a1d65a9349c38df.gif)
可以看到,
1.需要等待回调1,2执行完,才能执行postend输出;
2.方式1执行在线程(number=3),和post的线程一样,方式2执行在主线程。
也就是说,
1.在发布对象可以恢复其执行线程之前,它必须等待通知中心将通知分派给所有观察者;
2.如果不改变回调线程,默认回调执行在post的线程;
3.如果改变了回调线程,回调在主线程,post方法是同步的。
2.异步
如果回调是异步的形式,效果上可以实现异步。注意block模式是同步的,请自行测试。
但是真正的异步,官方提供了通知队列。
通知队列
NSNotificationQueue对象,或简单地说,通知队列,充当通知中心(实例NSNotificationCenter)的缓冲区。该NSNotificationQueue为Foundation Kit的通知机制提供了两个重要功能:合并通知和异步发布。
通知队列基础
通知队列NSNotification通常以先进先出(FIFO)顺序维护通知(实例)。当通知上升到队列的前端时,队列将其发布到通知中心,通知中心又将通知分派到注册为观察员的所有对象。
每个线程都有一个默认通知队列,该通知队列与该进程的默认通知中心相关联。您可以创建自己的通知队列,并且每个中心和线程都有多个队列。
open func enqueue(_ notification: Notification, postingStyle: NotificationQueue.PostingStyle, coalesceMask: NotificationQueue.NotificationCoalescing, forModes modes: [RunLoopMode]?)
public enum PostingStyle : UInt {
case whenIdle //线程空闲,异步
case asap //下一次runloop,异步
case now //马上执行,同步
}
通过设置不同的PostingStyle参数即可实现异步发布通知,
注意:如果这种异步方式没有接收到通知,很可能是线程已经销毁,应该把该线程设置为常驻线程。
let runloop = RunLoop.current
runloop.add(Port.init(), forMode: .commonModes)
runloop.run()
如果要改变回调线程,除了在回调方法里开启新线程外,苹果示例提供了一种线程间通信,通过port重定向,转发通知。向指定线程发送通知,更好的方式是实现一个NSNotificationCenter的子类或者一个单独的类来处理这些操作。
网友评论