Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

memory management - img_data_lock iphone - imageNamed vs imageWithContentsofFile

I am noticing a surge in memory and the responsible caller as listed in instruments is img_data_lock and responsible library is CoreGraphics.

I have been reading that the issue relates to cached vs not cached image load (Difference between [UIImage imageNamed...] and [UIImage imageWithData...]?) Currently my app loads a series of images via imageNamed

replacing the imageNamed call with imageWithContentsOfFile seems to solve the issue.

Does anybody have any information about the img_data_lock caller ? Why would someone use imageNamed if it takes such a toll on memory ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...