My iPhone app crashes after returning from backgro

2019-08-17 12:03发布

问题:

First off, I want to say this site is AWESOME! and it helped me do lots of stuff while creating my iPhone app.

Now, my problem is:

When I launch my app, I have a UIImageView that loads an image depending on an if/else statements in

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

method. These images are assigned as follows:

BG.image = someImage;

of course, BG is the UIImageView, and someImage is an iVar with @property, @synthesis. someImage is initialized with an image from the main bundle in viewDidLoad:

- (void)viewDidLoad {

//init stuff from file
someImage = [UIImage imageNamed:@"FirstViewBG_5N.png"];

[super viewDidLoad];}

My app runs happily, loading images according to touchBegan (as mentioned), BUT!

When my app is sent to background and comes back, it crashes upon first touch.

When I replaced:

BG.image = someImage

with:

BG.image = [UIImage imageNamed:@"FirstViewBG_5N.png"];

it runs happily?! I think the someImage is flushed or corrupts?

I don't want to leave it like this because imageNamed method reads from disk every time, which will cause performance problems, i think?

I think my question is clear? It is that:

1- Why will my app crash after returning from backgroud 2- How do I solve this?

All your help is appreciated! Thanks!

回答1:

I'm guessing the crash is EXC_BAD_ACCESS (but am guessing because you didn't post that information).

If "someImage" is an instance variable, you should synthesize it and use its accessor (self.someImage) so it is retained or copied. As it stands, you're assigning something to someImage but it's gone by the time you're trying to access it later.



回答2:

When you do this:

- (void)viewDidLoad {

    //init stuff from file
    someImage = [UIImage imageNamed:@"FirstViewBG_5N.png"];

    [super viewDidLoad];
}

The imageNamed method is returning an autoreleased object which gets cleaned up by the garbage collector after viewDidLoad returns. Try either retaining it:

    someImage = [[UIImage imageNamed:@"FirstViewBG_5N.png"] retain];

or using your synthesized setter which will retain it automatically:

    [self setSomeImage:[UIImage imageNamed:@"FirstViewBG_5N.png"]];

or using UIImage's initWithData initializer:

    someImage = [[UIImage alloc] initWithContentsOfFile:@"FirstViewBG_5N.png"];

All are functionally equivalent. #2 or #3 is best.

Apple's "Memory Management Rules" guide will save your life: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html%23//apple_ref/doc/uid/20000994-BAJHFBGH