Sobes.tech
Junior

Qu'est-ce que le centre de notifications?

sobes.tech IA

Réponse de l'IA

Le centre de notifications, ou NotificationCenter, est un mécanisme dans Foundation qui implémente le modèle "Observateur" (Observer). Il permet aux objets de diffuser largement des notifications à d'autres objets qui y sont abonnés.

Composants clés :

  • Publisher (Émetteur) : Objet qui publie la notification.
  • Observer (Observateur) : Objet qui s'abonne à la notification et y répond.
  • Notification (Notification) : Objet représentant l'événement lui-même. Contient le nom de la notification, l'expéditeur et un dictionnaire optionnel d'informations utilisateur.

Avantages :

  • Faible couplage entre objets.
  • Pratique pour diffuser des événements à de nombreux abonnés.

Inconvénients :

  • Complexité de débogage due à l'interaction indirecte.
  • Problèmes potentiels dans la gestion du cycle de vie des observateurs s'ils ne sont pas correctement supprimés.

Exemple de publication et d'abonnement :

import Foundation

// Nom de la notification
extension Notification.Name {
    static let myCustomNotification = Notification.Name("myCustomNotification")
}

// Émetteur
class Publisher {
    func publishNotification() {
        let userInfo: [AnyHashable: Any] = ["data": "some important data"]
        NotificationCenter.default.post(name: .myCustomNotification, object: self, userInfo: userInfo)
        print("Notification publiée")
    }
}

// Observateur
class Observer {
    init() {
        // Abonnement à la notification
        NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: .myCustomNotification, object: nil)
    }

    // Méthode appelée lors de la réception de la notification
    @objc func handleNotification(_ notification: Notification) {
        print("Notification reçue!")
        if let userInfo = notification.userInfo {
            print("Informations utilisateur : \(userInfo)")
        }
    }

    deinit {
        // Désabonnement de la notification lors de la désinitialisation
        NotificationCenter.default.removeObserver(self)
    }
}

// Utilisation
let publisher = Publisher()
let observer = Observer()

publisher.publishNotification()