-1

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

Michael Dorner
  • 17,587
  • 13
  • 87
  • 117

1 Answers1

0

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.

Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127
  • That contradicts what Apple claims: "The block is copied by the notification center and (the copy) held until the observer registration is removed." And furthermore: then I would not see more and more notification-prints, right? – Michael Dorner Jan 01 '17 at 14:10
  • NotificationCenter is purely 'in memory'. It does not store observers or callbacks to disk, so that they may survive app restarts. This should be especially clear when using blocks. Blocks (or closures) capture the scope in which they are created. If NC stored those blocks across app restarts, it would have to capture your entire app session all the time. @LarsBlumbergs answer is correct. There is another reason you are seeing more and more notifications. – CodingMeSwiftly Jan 01 '17 at 14:18
  • Sorry, but it is not the answer. First of all, this has nothing to about persistency. Meanwhile I found another guy who struggled into the same problem: http://sealedabstract.com/code/nsnotificationcenter-with-blocks-considered-harmful/ f – Michael Dorner Jan 01 '17 at 14:27
  • Maybe you want to clarify your question then? – Lars Blumberg Jan 01 '17 at 14:32