开发环境
XCode 14 Beta Macos 13 Mac os App SwiftUI
使用方法
- 定义事件名称,并先注册一下
//定义事件名称,后面以其为标志接收通知
static let SHOW_ALERT = "ShowAlert"
//OperationQueue.main为主线程,收到通知之后会在主线程触发,notification就是自己收到的object
NotificationCenter.default.addObserver(forName: NSNotification.Name(NotificationEvent.SHOW_ALERT), object: nil,
queue: OperationQueue.main) {[self] notificationObj in
//do something
}
- 发送通知事件,这个简单不用多说
NotificationCenter.default.post(name: NSNotification.Name(NotificationEvent.SHOW_ALERT), object: notificationObj)
一些注意事项
在SwiftUI中,默认使用struct作为主UI对象,UI对象的Init会被多次调用,所以尽量不要在Init中注册通知,不然会发生收到多次通知的情况,内存泄漏什么的。
一种解决方法是在Ui显示时订阅通知,在UI消失时取消订阅:
//在UI声明之后添加
.onAppear(){
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(NotificationEvent.SHOW_ALERT), object: nil)
NotificationCenter.default.addObserver(forName: NSNotification.Name(NotificationEvent.SHOW_ALERT), object: nil,
queue: OperationQueue.main) {[self] notification in
notificationAction(notification:notification)
}
}
.onDisappear(){
NotificationCenter.default.removeObserver(self)
}
近期评论