How to safely removeObserver (Swift)

后端 未结 2 988
生来不讨喜
生来不讨喜 2021-02-19 21:23

I have added an observer

override func viewDidLoad()
{
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector:\"selector na         


        
相关标签:
2条回答
  • 2021-02-19 22:01

    I think you should use code

    NSNotificationCenter.defaultCenter().removeObserver(self)
    

    Explain: You have mistake here: You are using NSNotification & NSNotificationCenter so you have to using this code above to remove observe. you have use code for KVO to remove observer so it will wrong.

    More detail you can read at here. Key-Value-Observing

    0 讨论(0)
  • 2021-02-19 22:02

    If you support iOS Versions by 9.0 you don't need to remove observers by yourself in your deinit method.

    Taken from the documentation

    In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated.

    https://useyourloaf.com/blog/unregistering-nsnotificationcenter-observers-in-ios-9/

    0 讨论(0)
提交回复
热议问题