开发者

UIButton setBackgroundImage consumes doesn't release memory?

My UIButton has it's background image set like this:

[myImageButton setBackgroundImage:[UIImage imageNamed:myImageName] forState:UIControlStateNormal];

myImageButton is a retained property of the class, and is setup with IB. No where else is it accessed in the app.

myImageName is simply an NSString with a filename like @"myImage_number_1.png"

I am loading large images, 1024 x 1024 in size. When the view is shown, it changes the image with the above statement, the开发者_如何学编程n available memory decreases.

After I see the view about 7-9 different times, the app crashes with a memory warning.

I thought the method would free up the loaded image.

The view itself is only instantiated and allocated one time, so it's not in the retain/release cycle if the view controller.

Is there something about this setBackgroundImage I don't know that causes it to not release memory?


Ah, found it. Every time imageNamed is used to load an image, it caches the image in memory. I switched to imageWithContentsOfFile - it doesn't cache images.


To future coders, @just_another_coder answer is correct, but there's something you all should know.

[UIImage imageNamed:myImageName] 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.

[UIImage 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.

So you should think about which one you'd rather, and if you use imagewithcontentsoffile you should remember to nil out that button otherwise you'll be doomed to an ever growing app (memory usage wise)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜