How can I get an EXC_BAD_ACCESS in a UIViewController's didReceiveMemoryWarning?

1k views Asked by At

I'm implementing didReceiveMemoryWarning in a subclass of UIViewController. My code looks something like the following:

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [self cleanUp];
}

When my app actually received a memory warning, the app crashed with an EXC_BAD_ACCESS on the [self cleanUp] line (a method that does exist). How could this happen? As I understand it, the framework called the didReceiveMemoryWarning method, then released my class before it attempted to execute [self cleanUp]. Why would this happen? How can I prevent this?

3

There are 3 answers

1
Josh Brown On BEST ANSWER

The crash was actually happening inside the -(void)cleanUp method, though Xcode was pointing to the line that called [self cleanUp]. Inside the -(void)cleanUp the code was accessing elements in an array that were already released, hence the EXC_BAD_ACCESS. Thanks to all for the helpful suggestions.

0
Rayfleck On

Wild guess: call [self cleanup] first, then call super. You can also simulate memory warnings in the sim, if that helps.

1
Steve Madsen On

Are you doing anything unusual in your view controller? What is the value of self when the crash occurs? Does it happen in both debug (optimization off) and release builds?

Try running with NSZombieEnabled. If this is a problem with unbalanced retain/release, that should help you find it.