斯威夫特 3 和 4
Swift 3 和现在的 Swift 4 已将许多“字符串类型”API 替换为struct
“包装类型”,与NotificationCenter 的情况一样。通知现在由struct Notfication.Name
而不是通过String
。有关更多详细信息,请参阅现在的遗产迁移到 Swift 3 指南 https://swift.org/migration-guide-swift3/#sdk-1
斯威夫特2.2 usage:
// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"
// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)
// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)
斯威夫特 3 和 4 usage:
// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)
所有系统通知类型现在都定义为静态常量Notification.Name
; i.e. .UIApplicationDidFinishLaunching
, .UITextFieldTextDidChange
, etc.
你可以延长Notification.Name
使用您自己的自定义通知,以便与系统通知保持一致:
// Definition:
extension Notification.Name {
static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)
斯威夫特 4.2 usage:
与 Swift 4 相同,但现在系统通知名称是 UIApplication 的一部分。因此,为了与系统通知保持一致,您可以扩展UIApplication
使用您自己的自定义通知而不是Notification.Name:
// Definition:
UIApplication {
public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)