0

I am having serious issues with memory when loading images to table view cells. What is the proper way to use autoreleasepool to correct the issue? I have tried:

for i in 0 ..< 5 {
    autoreleasepool {
        for j in 0 ..< 1000 {
            image = UIImage(data: data)
            dispatch_async(dispatch_get_main_queue(), {
                if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                    // cellToUpdate.imageView?.image = image
                    cell.imageView!.image = image
                }
            })
        }
    }
}
codersl
  • 2,222
  • 4
  • 30
  • 33
  • I'm unclear what you're trying to do here. Are you trying to exaggerate the problem with this loop? This doesn't look like the real problem to me. The `autoreleasepool` is useful when doing loop with autorelease objects, but this looks like contrived example. More likely, it's an attempt to use high res images in table view cells (memory corresponds to dimensions of image, not the size of the image view nor of the size of the `NSData`) or holding these `NSData` or `UIImage` objects in memory. – Rob Mar 28 '15 at 04:12
  • Assuming the above is contrived example, why don't you describe original problem more clearly (dimensions of images, the model backing the view, etc.). – Rob Mar 28 '15 at 04:16
  • Rob, that is the issue then. Amazing that you realized that. The images are larger 300x300 at least, and I am trying to put them into a table view cell. Is there a way to accept large images into cell.imageView.image? – Teb Theestatebook Mar 28 '15 at 04:17
  • PERACS, what do you think? Am I going to have to resize on back-end or can swift shrink? – Teb Theestatebook Mar 28 '15 at 04:22
  • 1
    One would generally want to resize the images when you set the `image` property of the image view. At first blush, this question looks very different, but I think the principles in the answer may apply here: http://stackoverflow.com/a/29311603/1271826. If you want to resize in Swift, this is my resizing code ported to Swift: http://stackoverflow.com/a/28513086/1271826. Bottom line, if the client needs larger images anyway, the resize in Swift. If you don't need high res at all, then maybe resizing on server side makes sense. Depends upon your app. – Rob Mar 28 '15 at 04:23
  • PERACS, how can we do this in swift? http://stackoverflow.com/questions/10491080/uiimage-resizing-not-working-properly/10491692#10491692 – Teb Theestatebook Mar 28 '15 at 04:27

1 Answers1

2

i used this kind of structure in my code it will help you resolve your problem :

func tooManyPictures() {
    let file = pathForResourceInBundle

    for _ in 0 ..< 5 {
        autoreleasepool {
            for _ in 0 ..< 1000 {
                let image = NSImage(contentsOfFile: file)
            }
        }
    }
}
codersl
  • 2,222
  • 4
  • 30
  • 33
Ribelyn Punk
  • 159
  • 1
  • 14