13

I have added an observer

override func viewDidLoad()
{
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector:"selector name", name: "observer name", object:nil)
    ...
}

When removing observer in deinit,

deinit
{
    NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
}

the app sometimes crashes:

Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer "class" for the key path "some string" from NSNotificationCenter because it is not registered as an observer.


So I am trying to add do/catch

deinit
{
    do{
        try NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
    }catch{}
}

But I get a warning:

catch block is unreachable because no errors are thrown in do block

And the app crashes


and when I am adding a try

deinit
{
    do{
        try NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: <some string>)
    }catch{}
}

I get this warning:

no calls to throwing functions occur within try expresion

And the app crashes

How should that be done?

Luda
  • 7,282
  • 12
  • 79
  • 139

2 Answers2

11

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/

Ilker Baltaci
  • 11,644
  • 6
  • 63
  • 79
  • FYI This is the [official documentation](https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver). And be aware that it is the observer on NotificationCenter who will be removed by the system automatically. – Michael Revlis Nov 18 '22 at 02:53
  • @MichaelRevlis "If your app targets iOS 9.0 and later or macOS 10.11 and later, and you used addObserver(_:selector:name:object:), you do not need to unregister the observer. If you forget or are unable to remove the observer, the system cleans up the next time it would have posted to it." – Ilker Baltaci Jan 27 '23 at 12:38
5

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

vien vu
  • 4,277
  • 2
  • 17
  • 30