Bootstrap

swift通知 NotificationCenter的使用

1.扩展通知的名字方便使用

//通知名字扩展
extension Notification.Name {
    //更新视图
   static let MyNotificationUpdateViewController = Notification.Name(rawValue:"updateViewController")
}

2.注册通知/移除通知

//创建通知中心,设置监听的方法
NotificationCenter.default.addObserver(self, selector: #selector(updateViewController), name:NSNotification.Name.MyNotificationUpdateViewController, object: nil)

//出现内存警告时
override func didReceiveMemoryWarning() {
     //移除通知
     NotificationCenter.default.removeObserver(self)
 }

3.发送通知

//不带参数
NotificationCenter.default.post(name:NSNotification.Name.MyNotificationUpdateViewController, object:nil)

//带参数
NotificationCenter.default.post(name: NSNotification.Name.MyNotificationUpdateViewController, object: nil, userInfo: ["post":"NewTest"])
;