Technology Musings

Debugging EXC_BAD_ACCESS on the iPhone

JB

I've been working on my first real iPhone app.  It's a very interesting way of coding.  Objective-C is an interesting language.  It seems to shoot for the middle ground between something out-of-control like C++, and something so-object-oriented-it-hurts like Java.  Personally, I like Ruby best, but that's neither here nor there.

Memory management on the iPhone is a tough cookie for someone who has not done Objective-C development before.  If you are new to the iPhone, the first thing you should do is read the memory management contract for Cocoa, as well as the links that link out from there.

I was having a problem getting EXC_BAD_ACCESS.  I finally used breakpoints to find where the problem was occurring, and it was an NSArray that was causing it.

I did a google search, and found this really cool method for getting a little more information about objects which have been released before they were accessed.

Eventually, I found out that the problem came from the fact that [NSArray arrayWithObjects:], because it doesn't have "init" or "copy" or "alloc" in the message name for object creation, autoreleases the object when it gives it to me!  Therefore, as soon as the present event was done, it trashed the object.  If you want to keep an object that has been autoreleased, you have to send it a retain message.

Doing the retain fixed my problem.  Yay!