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