0

I have an app that allows a user to go into their gallery and select photos from their photo library to add to the app, it is displayed in a tableview

This is then added to an array which after UIImagePickerController fetches the image, reloads the collection view with the new images.

My problem is that this uses large amounts of memory. I need a way to display the photos added exactly like the native photos app on the iPhone.

I've looked in lazy loading but I have no idea where to begin.

Could someone please tell how I would go about displaying images in a UICollectionView with lazy loading, or at least reducing the amount of memory used.

The app is generally at normal use using around 10mb of memory. This increases to 50mb+ when displaying a multitude of images in the collectionView.

Thanks.

  • Create a thumbnail and save it. Use [`imageNamed`](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/clm/UIImage/imageNamed:) for its cache. – Marcus Adams Feb 05 '15 at 18:45

1 Answers1

2

Holding high-resolution images into an array will generally be problematic. Also, using the full resolution images for thumbnail sized image views in collection view is an extravagant use of memory.

So, when the user selects an image, capture a reference to that asset's URL. Then, as images are required by cellForItemAtIndexPath, retrieve the image, resize it to thumbnail dimensions (e.g. you could use something like this) and use that in your cell's image view.

If you want to be elegant about it, implement a NSCache in which you'll cache previously resized images, but make sure you have reasonable retention rules and have that purge itself upon memory pressure. That way, cellForItemAtIndexPath can see if the image exists in its cache, and if so, use that, otherwise go back to the assets library and resize that image. But by using cache, you can speed up the process of scrolling back through images that were previously resized.

But the key is to avoid holding high resolution images in memory. And if you're going to hold even the thumbnails in memory, you might want to capture that in something like a NSCache rather than an array.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044