简体   繁体   中英

iOS - How to avoid memory leak when saving and loading images to display in UITableView?

So this is more of a conceptual architecture question. I'm making a messaging app in iOS. Devices can send image messages. I am saving custom Message objects (which include images) to disk using NSCoder protocol. I want to remove the messages from memory when I don't need them (ie when the user logs out and disappears from users list view). I am appropriately encoding that user's messages to disk, and loading them when the user re-appears. However, on the messaging view (a dynamic UITableView where each cell displays the message content), the image content of the messages are cached within the UIImageView subview.

So, I am essentially creating duplicates of the images when I load the messages from disk. Every time a user logs out and then in (ie disappearing and then reappearing), the associated messages are saved and then loaded from disk (recreated objects), and my memory usage creeps upward once I go to the private message view and scroll all the way up in order to display all messages.

Ultimately, I want to clean the cache of message images so that I can free up memory when a user is no longer around. I have a good reason for saving messages locally; my question is: what is the best design for saving messages/images to disk, removing them from cache memory, then reloading them when I need to populate a dynamic UITableView ?

I'd advice you to use some ready caching library like: SDWebImage , FastImageCache or Haneke . All of them are both using disc and memory cache, what will improve the speed of your tableView and decrease number of download requests.

You can of course make your custom solution, but it won't work as well as something written during months and tested via many developers. However if you want to, I'd suggest to take a look into one of these libraries and start by considering what they've done to make everything 'speedy'.

This way you just save URL in your Message instead of full image. These libraries will check URL, understand that they already have the image in memory cache and load it. You don't have to store it in your array of objects nor download again or save by yourself on disc.

Keeping your message objects on the disc seems weird, as this is slow - better to use database - CoreData/Mantle/FBDB etc, however that's your decision :) Also storing on the disc makes your Messages very easy to reverse engineering attacks and isn't safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM