开发者

iOS UIImageView Memory Problem

开发者 https://www.devze.com 2023-02-21 11:08 出处:网络
I\'ve been trying to solve a problem to do with the image in my UIImageView being released due to memory warnings.

I've been trying to solve a problem to do with the image in my UIImageView being released due to memory warnings.

Here's my situation:

1) I declare a U开发者_JS百科IImageView in my .H:

IBOutlet UIImageView *fightStyleImage;
...
@property (nonatomic, retain) UIImageView *fightStyleImage;

2) I synthesize and dealloc in my .M:

@synthesize fightStyleImage;
...
...
-(void)dealloc{
[fightStyleImage release];
...
}

3) I attach the fightStyleImage to a UIImageView in Interface Builder.

4) Part of my app's experience allows a user to swipe on the device, to cycle through 5 different images. I am using the following code to achieve that:

// Load next image
UIImage *theImg = [UIImage imageNamed:@"fighter1.png"];
fightStyleImage.image = theImg;

Everything works really well, and I'm happy with the performance, experience, etc.

However, when I pop to another view controller (or to an MFMailComposeViewController, or an Address Book picker) and my device receives a memory warning (either through the simulator, or on the device), the following happens when I return to my original view controller: the iOS seems to jettison my UIImageView image (I assume because it is the most expensive object in memory), and I am left with a black screen (i.e. no image). If I begin to swipe again, the images return and continue to cycle properly.

I'd love to hear any thoughts on this, and thanks in advance for any solutions/insights anyone might have. In particular, I'm interested (of course!) in restoring my image that has been jettisoned from memory.

-SD


You need to properly implement the viewDidLoad and the viewDidUnload to setup and release your views. Read the iOS section of the Memory Management Programming Guide for assistance. I also recommend you move your IBOutlet declaration from the ivar to the property as so

UIImageView *fightStyleImage;
...
@property (nonatomic, retain) IBOutlet UIImageView *fightStyleImage;


The problem maybe due to using imageNamed: method as it caches the images into your memory and will be forced to free only when Low Memory warning occurs. Better go this way:

UIImage *image=[[[UIImage alloc]initWithContentsOfFile:imagePath]autorelease];
0

精彩评论

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