Stupid Cocoa Bugs: Bad Access

That is to say, bugs in my Cocoa code that are stupid–not stupid bugs in Cocoa itself =]

After updating something trivial in my iPhone app, I started getting EXC_BAD_ACCESS crashes on the device–but only when it wasn’t hooked up to the debugger. I found out that the error happened in the dealloc method of one of my UIViewControllers, on a line where I release one of the object’s property objects. I checked all my code and it seemed like I was following standard memory management rules.

The solution ended up being dumb: at some point I had gotten it into my head that I was supposed to call the superclass’s dealloc method, then release the properties:

-(void)dealloc {
    [super dealloc];
    [myProperty release];

But, when I looked in the Memory Management Programming Guide, it seems that you’re supposed to release your properties first:

-(void)dealloc {
    [myProperty release];
    [super dealloc];

This makes sense, assuming that at some point up the superclass chain the object itself gets released or free’d.

The crazy thing was that I’d used the wrong order for the app for over a week without any crashes. I guess this is part of what a JVM guy like me needs to learn about memory management: the problems don’t always show up reliably or right away.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: