How to post and receive an NSNotifications (Objective C) | Notifications (in Swift)?

后端 未结 3 1406
遥遥无期
遥遥无期 2020-12-03 02:56

Is there an easy-to-grock pattern how to send a NSNotification (Objective C) | Notification (in Swift) and how to receive one? Code snippet? The docs write like 150 pages on

3条回答
  •  臣服心动
    2020-12-03 03:47

    Swift Version for the same :

    Whenever you need to post the notification :

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UpdateAccepted"), object: self)
    

    On controller where you want to receive the notification :

    override func viewDidLoad(_ animated: Bool) {
        super.viewDidLoad(true) {
        NotificationCenter.default.addObserver(self, selector: #selector(updateAccepted(notification:)), name: NSNotification.Name(rawValue: "UpdateAccepted"), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "UpdateAccepted"), object: nil)
    }
    
    @objc func updateAccepted(notification: Notification) {
        handleRefresh()
    }
    

提交回复
热议问题