views:

14301

answers:

5

I want to load some images into my application from the file system. There's 2 easy ways to do this:

[UIImage imageNamed:fullFileName]

or:

NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *imageData = [NSData dataWithContentsOfFile:fileLocation];

[UIImage imageWithData:imageData];

I prefer the first one because it's a lot less code, but I have seen some people saying that the image is cached and that this method uses more memory? Since I don't trust people on most other forums, I thought I'd ask the question here, is there any practical difference, and if so which one is 'better'?

I have tried profiling my app using the Object Allocation instrument, and I can't see any practical difference, though I have only tried in the simulator, and not on an iPhone itself.

+24  A: 

It depends on what you're doing with the image. The imageNamed: method does cache the image, but in many cases that's going to help with memory use. For example, if you load an image 10 times to display along with some text in a table view, UIImage will only keep a single representation of that image in memory instead of allocating 10 separate objects. On the other hand, if you have a very large image and you're not re-using it, you might want to load the image from a data object to make sure it's removed from memory when you're done.

If you don't have any huge images, I wouldn't worry about it. Unless you see a problem (and kudos for checking Object Allocation instead of preemptively optimizing), I would choose less lines of code over negligible memory improvements.

Marc Charbonneau
+1  A: 

I've also been told that [UIImage imageNamed:] does a little bit too much caching, and images are not often released. I was told to be careful of using it.

Ben Gottlieb
I got in trouble with the caching. My app was loading images, then over-writing the image file, and that ended up causing really oddly messed up images and scary debug messages from the JPEG library.
Chris Lundie
+1  A: 

In my experience [UIImage imageNamed:] has dramatically better performance, especially when used in UITableViews.

It's not just the memory but also decoding the image. Having it cached is much faster.

Hunter
Even more important is the reuseIdentifier on cells - if you don't reuse table cells performance will suffer.
Kendall Helmstetter Gelner
A: 

imageWithData is useful when you store your image binary in a database or progressively downloading large image from the web.

Dan
A: 

Ben Gottlieb, are you suggesting that cached memory (from loading via imageNamed) is unreliable? How can the system allow an image to be over-written, even if it is in cache (unless that image is no longer referenced). Im interested because i seem to be having a similar issue.

AlvinfromDiaspar
don't use answers for discussions
hop