I agree with “depending on the scenario”. If it was a fixed number of something small, as your example of “5 integers” suggested, I’d totally agree. I’d call that a “fixed cost” or “overhead” and not a “leak”.
As currently implemented, it’s an ever growing number of objects in memory that increases based on repeated execution of some code (triggered by user action in this case) and thus a memory leak. It is exactly a case of “memory is not released,” as you say. A retain cycle is one common cause of memory leaks, but certainly not the only one. “Failing to dispose of something that should be” is another. That’s a less common one now that we have ARC, but still possible, as this code demonstrates.
Now, I’ll be the first to agree that this is not very likely to be an issue in this app (unless it retains the whole publisher memory tree or something nasty like that). I mean, how many times is a user going to hit the add photos button (or save etc), realistically?
The reason I’m bothering to push on this, and care, is because this is likely to be an often-read book and teaching good memory management habits is important in that context. For a quick hack-test then there is no reason to care.
Imagine a scenario where someone wrote a photo processing app that processed a large batch of photos and re-used the PhotoWriter.swift file from this project. If they copied the code in
actionSave()from MainViewController.swift which uses PhotoWriter to save an image and which follows the same pattern of saving the
AnyCancellable into the
Set, then this memory leak is a lot more likely to be a significant problem for them (particularly if the number of photos processed is large).
Your idea of setting up the subscription once is interesting. Not sure how it works since the publisher goes away when the
PhotosViewController is dismissed (presumably). Likewise for the other places where the
AnyCancellable is saved into the
PhotoWriter which uses a transitory
Future publisher, etc).
Thanks again for the reply. Onward!