Why delete old images from BNRImageStore?


#1

I’m somewhat confused as to why we want to check for and delete old images before replacing them with a newer one.

I can see why I’d do this if I wasn’t using ARC, but wouldn’t ARC take care of releasing the old image as it would no longer be pointed to within memory when the new image is assigned to the same variable?

Is it actually more memory efficient to beat ARC to it or am I missing something else?


#2

It’s a best practice.

In the case of our app as it stands now, we are storing the images in an object in memory, but that’s not a real-world scenario (more on that in a minute.) Even still, we want to be careful of our memory consumption. Imagine if it was a different app where lots of images were getting stored in memory, and we never manually cleaned up after ourselves (think of a web browser, loading pages.) As a user continues using our app, we will end up consuming all of the memory, and making the device run slow.

In a real app, the images would get stored to a database of some sort. It would be a safe bet that as our project continues, we will implement some kind of file system storage for the photos. Since these photos are user data and not a cache, the OS will never clean them itself, even after we stop referencing one (databases don’t use ARC – items are only removed when we tell them to be.) If a photo is removed, we want to remove the photo not only from the UI, but from the file system as well. If we don’t, we could end up needlessly consuming all of the users storage space.


#3

Thanks for the explanation. That makes a lot of sense.

Thank you.


#4

ARC won’t take care of this for you because a unique UUID is created for each and every picture.

So the new picture you just took gets its own UUID - which is different from the old key and therefore won’t overwrite the old key in the dictionary.

So the old picture will still be sitting there with the old key/value pair unless you do this clean-up.

Although BNRItem no longer has a strong reference to that key, BNRImageStore’s dictionary (the singleton you created) does still have a strong reference to the old picture - and that’s what you have to clean-up here with this code. Otherwise you’ll be creating endless pictures with continuous strong references from the singleton’s dictionary.