iOS4 calling ImageNamed: still leak or cause memor

2020-07-27 17:13发布

问题:

So apparently, my app crashes on ipod 2nd generation due to low memory issue. What I do was calling image on each view within scrollView + pageControl when user scrolls. And app crashed when it reached a particular point after got memory warning. I tried to free up view when I got warning but it still caused crash.

I googled about ImageNamed: and apparently there was issue within this api call, but most article said it was fixed in recent iOS version.

I fixed this problem with calling image imageWithContentOfFile instead imageNamed, but I'm wondering if ImageNamed still causes memory leak or not free up when it view is released.

回答1:

imageNamed: doesn't cause a leak, but it is frequently misunderstood which is what leads to memory issues when it's used. It caches the uncompressed image after it is loaded, which means there are immediately 2 copies of that image in memory. If you use it for small, frequently used images (such as icons), this is great because the runtime doesn't have to fetch the file off disk - it's already available in the cache. Where this gets users into trouble is when they use imageNamed: to load a large image, say a 4MP image taken with a camera. That image takes up quite a bit of memory: 4 million pixels, types 4 bytes per pixel = 16MB of memory, TWICE. If you use that method to load images for your slideshow, photo sharing, camera app, or whatever, it adds up real fast.

So if those features don't fit what you need, use one of the other UIImage loading methods. You users will thank you.

Note: This information comes from the Apple Engineer which presented the UIKit rendering session (#121 I think it was). Hopefully my notes are correct :)