Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between [UIImage imageNamed...] and [UIImage imageWithData...]?

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.

like image 997
rustyshelf Avatar asked Nov 25 '08 02:11

rustyshelf


2 Answers

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.

like image 83
Marc Charbonneau Avatar answered Sep 28 '22 06:09

Marc Charbonneau


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.

like image 36
Hunter Avatar answered Sep 28 '22 06:09

Hunter