问题描述
我注意到内存激增,仪器中列出的负责调用者是img_data_lock,负责的库是 CoreGraphics
。
我一直在读这个问题与缓存与未缓存的图像加载有关
()目前我的应用程序通过 imageNamed
加载一系列图像p>
用 imageWithContentsOfFile
替换 imageNamed
调用似乎解决了这个问题。
有人有关于img_data_lock来电的任何信息吗?
为什么有人会使用 imageNamed
如果这会对内存产生这样的影响?
UIImage的方法imageNamed:和imageWithContentsOfFile:做一些略有不同的事情。 imageNamed将图像加载到特殊的系统缓存中,然后使用该图像路径的未来调用将返回缓存中的图像,而不是从磁盘重新加载它。 imageWithContentsOfFile只是在您指定的路径上加载图像,但不进行缓存。对同一图像多次调用imageWithContentsOfFile会在内存中产生多个副本。
iOS似乎没有清空缓存(好吧或根本没有,我不是当发出内存警告时,可能导致应用程序因缺少可用内存而被终止。装有imageWithContentsOfFile的UIImages通过清除它们的图像并在需要时重新加载它来响应内存警告,这可以解释为什么你的内存峰值消失了。
此外,缓存似乎是在模拟器中比在实际硬件中大得多,我在UIImages中使用imageNamed看到的问题和崩溃只发生在设备上。在模拟器上进行测试时要小心!
我在视图中多次使用可以看到使用imageNamed相同图像的唯一原因。或者,您可以实现自己的图像缓存,并获得可以控制的缓存的好处,如下所述:
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 ?
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/
这篇关于img_data_lock iphone - imageNamed vs imageWithContentsofFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!