0

I have several ViewControllers that indirectly subscribe to a global NotificationCenter instance, by calling this function that is part of a class of mine:

public func subscribeToValueChanges (key: String, callback: @escaping ()->Void)
{
    changeNotifier.addObserver (forName: NSNotification.Name(rawValue: key), object: self, queue: OperationQueue.main, using: { (n: Notification) in
        callback()
    })
}

(managed by , using addObserver(forName:object:queue:using:).

Now, I have to remember to invoke removeObserver when my viewcontroller gets freed, or I'll probably cause a leak. That's a bit unsafe.

I wonder if there is a way to automate this, so that the class that implements the above function can learn when the block's owner is freed. Or maybe even at the time the current ViewController disappears (there seems to be no global notification for that, or is there?)

Or would, by using [weak self] in the closure's code, callback become nil, so that I can perform an occasional garbage collection on all callbacks (by storing them as optionals in an array)?

Another thought: The ObjC runtime offers associated objects (How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?) – could those be attached to closures, perhaps? Then I might be able to monitor that object and learn when the closure is freed.

Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149
  • 1
    According to the documentation you are responsible for removing the observer, a possible solution is to add the observer in `viewWillAppear` and remove it in `viewDidDisappear` (I'm using that in a Core Data iCloud environment) – vadian Jun 10 '17 at 19:36
  • @vadian - yes, that's obvious. I am not trying to avoid removing the observer but I try to learn when it's time to do that, by not having to *remember* to write that second call in the many placed I'll be calling my subscribeToValueChanges function, because that's easy to overlook and therefore not a good strategy. Therefore, I like to solve the part inside that class that also manages the call of addObserver. It's all about locality. – Thomas Tempelmann Jun 10 '17 at 19:40
  • [This question](https://stackoverflow.com/questions/28689989/where-to-remove-observer-for-nsnotification-in-swift) mentions that `deinit` is the normal place to remove observers, and that as of iOS 9, when not using the block based observers, you don't even need to remove observers yourself anymore. – paulvs Jun 10 '17 at 20:35

0 Answers0