Swift 3 & 4
Swift 3, et maintenant Swift 4, ont remplacé beaucoup de "stringly tapé" Api avec struct
"wrapper types", comme c'est le cas avec NotificationCenter. Les Notifications sont désormais identifiés par un struct Notfication.Name
plutôt que par String
. Pour plus de détails, voir le désormais héritage Migration vers Swift 3 guide de
Swift 2.2 utilisation:
// 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)
Swift 3 & 4 utilisation:
// 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)
Tout le système de types de notifications sont désormais définies comme étant des constantes statiques sur Notification.Name
; .UIApplicationDidFinishLaunching
, .UITextFieldTextDidChange
, etc.
Vous pouvez étendre Notification.Name
avec vos propres notifications afin de rester cohérent avec le système de notifications:
// Definition:
extension Notification.Name {
static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)
Swift 4.2 utilisation:
Même que Swift 4, sauf que maintenant les notifications du système de noms font partie de UIApplication. Ainsi, afin de rester cohérent avec le système de notifications vous pouvez étendre UIApplication
avec vos propres notifications au lieu de Notification.Nom :
// Definition:
UIApplication {
public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)