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.