NotificationCenter的基本用法post方法一般用这两个。
open func post(name aName: NSNotification.Name, object anObject: Any?)
open func post(name aName: NSNotification.Name, object anObject: Any?, userInfo aUserInfo: [AnyHashable : Any]? = nil)
aName
aName是名称,定义一个类型为NSNotification.Name的全局常量,或者扩展NSNotification.Name即可。为了预防字符串重复,最好保持rawValue和常量名一致。例如:
let iAmANotificationName = Notification.Name(rawValue: "iAmANotificationName")
NotificationCenter.default.post(name: iAmANotificationName...)
这样一来,所有观察iAmANotificationName的对象都会收到这条post了。
object
object一般是在哪个类中调用post方法,就传哪个类。有的人喜欢用这个参数来传递参数,不是说不行,只是我感觉不太舒服。
userInfo
userInfo才是用来传参数的字段,[AnyHashable : Any]的范围足够你爱传什么传什么了。
参数调用
设计观察者方法时,记得加一个类型为Notification的参数,就可以用来接受notification,并读取object和userInfo了,非常简单。例如:
func receivedNotification(_ notification: Notification) {
let userInfo = notification.userInfo
let object = notification.object
...
}