Send and receive messages through NSNotificationCenter in Objective-C?

后端 未结 6 1503
感动是毒
感动是毒 2020-11-21 22:40

I am attempting to send and receive messages through NSNotificationCenter in Objective-C. However, I haven\'t been able to find any examples on how to do this.

6条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 22:43

    SWIFT 5.1 of selected answer for newbies

    class TestClass {
        deinit {
            // If you don't remove yourself as an observer, the Notification Center
            // will continue to try and send notification objects to the deallocated
            // object.
            NotificationCenter.default.removeObserver(self)
        }
    
        init() {
            super.init()
    
            // Add this instance of TestClass as an observer of the TestNotification.
            // We tell the notification center to inform us of "TestNotification"
            // notifications using the receiveTestNotification: selector. By
            // specifying object:nil, we tell the notification center that we are not
            // interested in who posted the notification. If you provided an actual
            // object rather than nil, the notification center will only notify you
            // when the notification was posted by that particular object.
    
            NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
        }
    
        @objc func receiveTest(_ notification: Notification?) {
            // [notification name] should always be @"TestNotification"
            // unless you use this method for observation of other notifications
            // as well.
    
            if notification?.name.isEqual(toString: "TestNotification") != nil {
                print("Successfully received the test notification!")
            }
        }
    }
    

    ... somewhere else in another class ...

     func someMethod(){
            // All instances of TestClass will be notified
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TestNotification"), object: self)
     }
    

提交回复
热议问题