开发者

how to keep an UIImage from disappearing after an app resumes from a background? (iPad)

I have an UIImage* loadedPoofSprite which I initialize like so:

NSMutableDictionary* loadedDictionary=[NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",Main_Bundle_Path,poofConfigFileName]];
NSString *textureFileName = [[loadedDictionary objectForKey:@"metadata"] valueForKey:@"textureFileName"];
loadedPoofSprite = [UIImage imageNamed:textureFileName]; 

poofImage = [[UIImage imageNamed:textureFileName] CGImage];

From there I use my poofImage and everything seems fine till my app resumes from a background. I get a crash 'cause loadedPoofSprite is gone. I thought the way to avoid this would be to retain loadedPoofSprite like so:

[loadedPoofSprite autorelease];
loadedPoofSprite开发者_如何学Python = [[UIImage imageNamed:textureFileName] retain]; 

This works but I was suggested it's not the right way to do it and I should basically load loadedPoofSprite again in applicationWillEnterForeground. I don't understand why it's better to load it twice instead of retaining it. What would be a right approach to deal with the above?

thanks!


If you would make loadedPoofSprite a retained property, and assign it like:

self.loadedPoofSprite = [UIImage imageNamed:textureFileName];

then all will be fine. A retained property is declared using

@property (nonatomic,retain) UIImage *loadedPoofSprite;

and you need to generate a getter/setter using

@synthesize loadedPoofSprite;

Then in the dealloc routine, add self.loadedPoofSprite = nil; to release the image when needed.


You don't specify what you do with your loadedPoofSprite/poofImage. Possibly the problem is not related to retain/release: e.g., if you add the image as a subview to another view (through an UIImageView), your image is automatically retained by the framework, so retaining it yourself should not be required and could prevent unloading it when the system needs it.

Indeed, it is possible that your application, while in the background, is affected by the system attempting to recover memory for the benefit of another app running; in such case, your views would be released, possibly deallocated, and on resume to foreground, your app would not find its views. Hence the failure.

If my reasoning applies, you will need to check whether your UIViews are there and be prepared to reload/recreate them as needed (as specified by the docs about didReceiveMemoryWarning/viewWillLoad/viewDidUnload).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜