Reputation: 2637
On iOS 6.1, I have a view controller with a scrollView in which I need to display some images as the user flicks through the pages. The scrollView has 3 subviews to display the current, the previous and the next image respectively. Images are substituted during the scrolling. The mechanism works fine, but resources are not released as expected and the app is terminated after scrolling approximately 15 images.
At first I tried solving the problem simply assigning the new image to the UIImageView, but it did not work (I read that images are cached), so I tried a different approach:
// access the UIImageView of the currentView
for (UIView *subviewOfCurrentView in [currentView subviews]) {
if ([subviewOfCurrentView isKindOfClass:[UIImageView class]]) {
UIImageView *cv = (UIImageView *)subviewOfCurrentView;
//cv.image = nil;
[cv removeFromSuperview];
UIImageView *new_cv = [[UIImageView alloc] initWithFrame:photoRect];
new_cv.image = [UIImage imageNamed:[myObject getFileName];
[currentView addSubview:new_cv];
}
}
Profiling the app with the Activity Monitor shows that the Real Memory Usage keeps growing when I flick an image, despite the fact that the number of subviews remains constant.
Note that the app is terminated without calling didReceiveMemoryWarning.
How can I force my app to release the memory used by UIImage(s) and UIImageView(s)?
If you can help me, much appreciated.
Upvotes: 2
Views: 3456
Reputation: 130092
UIImage
loaded by imageNamed:
are are not automatically released (they are cached and images with the same name share the same data).
Use imageWithContentsOfFile:
or imageWithData:scale:
if you want the image to be automatically released. Note that you can get the image path using methods from NSBundle
although it will be a bit more complicated.
You will have to implement the following part by yourself
If the screen has a scale of 2.0, this method first searches for an image file with the same filename with an @2x suffix appended to it. For example, if the file’s name is button, it first searches for button@2x. If it finds a 2x, it loads that image and sets the scale property of the returned UIImage object to 2.0. Otherwise, it loads the unmodified filename and sets the scale property to 1.0.
Not sure how to get path for an image when using the new iOS 7 image stores.
Upvotes: 5