What is the difference b/w imageNamed and imageWithContentsOfFile in ObjectiveC
-
2Well, they are different methods. I'm sure the documentation is useful in this case (as always). – Jul 10 '13 at 11:38
-
related: [Difference between `[UIImage imageNamed…]` and `[UIImage imageWithData…]`?](http://stackoverflow.com/questions/316236/difference-between-uiimage-imagenamed-and-uiimage-imagewithdata?lq=1) – Matthias Bauch Jul 10 '13 at 11:43
-
2Question isn't broad at all. It may not well worded, but it is quite specific. It may, however, be marked as a duplicate of the question that Matthias Bauch has presented above. – WolfLink Jul 11 '13 at 06:43
3 Answers
imageNamed: imageNamed cache’s your images and you lose control over the memory - there's no guarantee that releasing the object will actually release the image but does provide faster loading of images second time around as they are cached. If you are using Interface Builder, and setting the image in Image View Attributes, that is also equal to imageNamed method. The image will be cached immediately when the app is ran
imageWithContentsOfFile : imageWithContentsOfFile does not cache images and is more memory friendly however as it does not cache images and they are loaded much slower. imageWithContentsOfFile: requires you to put the full path. I don't see why imageNamed: wouldn't be recommended, besides the fact that you can't access files outside of the application bundle.

- 403
- 8
- 13
Got a nice link which explains the difference b/w these two methods image named-vs-image with contents of file

- 4,875
- 4
- 32
- 50

- 1,139
- 1
- 14
- 30
From this SO link
UIImage's methods imageNamed: and imageWithContentsOfFile: do slightly different things. imageNamed loads the image in a special system cache, and then future calls with that image path will return the image in the cache instead of reloading it from disk. imageWithContentsOfFile simply loads the image at the path you specify, but does no caching. Multiple calls to imageWithContentsOfFile for the same image will result in multiple copies in memory.
iOS doesn't seem to empty the cache (well or at all, I'm not sure) when a memory warning is issued, which can lead to apps being terminated for lack of free memory. UIImages loaded with imageWithContentsOfFile respond to memory warnings by purging their images and reloading it when needed, which might explain why your memory spike went away.
Also, the cache seems to be much larger in simulator than in actual hardware, the problems and crashes I've seen with UIImages using imageNamed have only happened on a device. Watch out when testing on the simulator!
The only reason I can see for using imageNamed the same image is used many times in your views. Alternatively, you can implement your own image cache, and get the benefits of having a cache that you can control, as described here: http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/
Check out this link as well.