Where to remove observer for NSNotification in Swift?

后端 未结 9 1416
你的背包
你的背包 2020-12-01 00:37

Where should I remove the observer for NSNotification in Swift, since viewDidUnload and dealloc() are unavailable?

相关标签:
9条回答
  • 2020-12-01 01:15

    Swift provides a deinit method that is called on instances of classes before they are destroyed.

    https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Deinitialization.html

    0 讨论(0)
  • 2020-12-01 01:16

    Use below method which functions same as dealloc.

    deinit {
        // Release all resources
        // perform the deinitialization
    }
    

    A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how intializers are written with the init keyword. Deinitializers are only available on class types.

    Swift Deinitializer

    0 讨论(0)
  • 2020-12-01 01:22

    In Swift 4.2, this is one of the way you can remove observer

    deinit {
        NotificationCenter.default.removeObserver(self, name: Notification.Name.Identifier, object: nil)
    }
    

    setup addObserver notification in viewDidLoad class

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(didReceivedItemDetail), name: Notification.Name.Identifier, object: nil)
    }
    
    0 讨论(0)
提交回复
热议问题