How can I ensure, that an observer within a NotificationCenter is called only once - especially when the app crashes/has to be stopped by Xcode?
Let's assume I want to print the notification NSNotification.WhatHaveYou
.
init() {
NotificationCenter.default.addObserver(forName: NSNotification.Name.WhatHaveYou, object: nil, queue: OperationQueue.main, using: { (notification) in
print(notification)
})
}
Which works fine.
Apple stated in its documentation for NotificationCenter.default.addObserver(forName:, object:, queue:, using:)
:
The block to be executed when the notification is received.
The block is copied by the notification center and (the copy) held until the observer registration is removed.
But how can I make this observer registration is removed, so that for the next app start there is no further notification registered?
Especially when the app crashes or I stop the application via Xcode, the observer is not removed, so the notification will show up multiple times - to be more precise: lastNumberOfOccurences = lastNumberOfOccurences +1
How to handle that properly?
Update
So far I find these resources
Observers that are subscribed to NotificationCenter cannot survive app restarts. This is because the objects that you've added get removed from memory as soon as the app dies, be it a crash or a normal termination. This said, all observers need to be added during runtime of your app and they can be also removed during your app's runtime. As soon as the app terminates, all associated memory gets freed, including subscribed observers.