开发者

IOS / iPhone loading images into UIImage based on slider value memory issue

I am loading images into a UIImage with the values of a slider (these are pages or slides, if you like). This UIImage switches them very fast with the use of a slider. Problem is, at some point, the app crashes on the device with an error of:

2011-04-02开发者_如何学C 17:39:01.836 Book1[2123:307] Received memory warning. Level=1

Here's the code:

- (IBAction)slidePages:(id)sender{
    int sliderValue = pageSlider.value;

    NSString *slideToPage = [NSString stringWithFormat:@"P%i.jpg", sliderValue];
    imagePlaceholder.image = [UIImage imageNamed:slideToPage];

    pageDisplay.text = [NSString stringWithFormat:@"Page %i", sliderValue];

    currentPage = sliderValue;  
}

Is there anything I could do to make it more efficient? Maybe the error is somewhere else but I'm guessing it has to do with the fast loading of images.

Still, I don't know how iOS deals with this. Every time I load a new image into the UIImage what happens with the "unloaded" one?

Thanks in advance.


One imortant aspect of [UIImage imageNamed] is that it caches all images loaded in that way and they never get unloaded, even if you dealloc the UIImage that was created! This is good in some circumstances (e.g. smallish images in UITableView cells), but bad in others (e.g. large images).

The solution is to use [UIImage imageWithData] which does not do this caching and which unloads the data when the UIImage is dealloc'd.

More info and discussion here:

Difference between [UIImage imageNamed...] and [UIImage imageWithData...]?

Update

This question has some good info on the question of [UIImage imageNamed:] not emptying its cache when a memory warning occurs.


[UIImage imageNamed:] caches images, so every image thus loaded effectively leaks. I don't know what the canonical solution is, but one option might be to load the image with CGImageCreateWithJPEGDataProvider() and initialise it with [UIImage imageWithCGImage:].


The original (wrong) answer:

You may need to release the previous image before loading the current one.


Loading a bunch of large images in iOS has always been a memory issue. As Marcelo mentioned, you should only keep around images are you currently viewing. All other images should be released so they can be garbage collected and the memory freed up. In my experience, even loading 2 fairly large images (500k-2mb each) will cause memory issues, especially on older devices with less RAM.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜