斯威夫特 4.0 和 Xcode 9.0+:
发送(邮寄)通知:
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
OR
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil, userInfo: ["Renish":"Dadhaniya"])
接收(获取)通知:
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
收到通知的函数方法处理程序:
@objc func methodOfReceivedNotification(notification: Notification) {}
斯威夫特 3.0 和 Xcode 8.0+:
发送(邮寄)通知:
NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
接收(获取)通知:
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
接收通知的方法处理程序:
func methodOfReceivedNotification(notification: Notification) {
// Take Action on Notification
}
删除通知:
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name("NotificationIdentifier"), object: nil)
}
斯威夫特 2.3 和 Xcode 7:
发送(邮寄)通知
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
接收(获取)通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)
接收通知的方法处理程序
func methodOfReceivedNotification(notification: NSNotification){
// Take Action on Notification
}
对于历史 Xcode 版本...
发送(邮寄)通知
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
接收(获取)通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil)
删除通知
NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self) // Remove from all notifications being observed
接收通知的方法处理程序
func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}
使用@objc注释类或目标方法
@objc private func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}
// Or
dynamic private func methodOfReceivedNotification(notification: NSNotification) {
// Take Action on Notification
}