Using “autorelease” can really bite you!

This will be a short post, but there was a lot behind it. Trust me!

A few times, I’ve run into cases where my code didn’t run as expected. I’d initialize an object (sometimes in viewDidLoad()). Later, maybe in viewWillAppear(), or in a button delegate, I’d try to access that object and use it. The debugger would show an EXC_BAD_ACCESS. I’d step through the code and sometimes, the object would appear normal in the inspector. Other times, the debugger would think it was of a different type!?!

The cause, it seems was that when I initialized the object, I set autorelease, like this;

memberVariable = [[[MyObject alloc] initWithParam:param] autorelease];

I thought I was being smart by allow the object to be cleaned up for me. In fact, I was causing a problem because I apparently don’t understand the behavior of autorelease. It turns out it can cause objects to be released early. I would say avoid autorelease! It has bitten me several times now!

Dismissing keyboard for UITextField

I found it frustrating that editable UITextFields don’t automatically dismiss the keyboard when editing is done. I think this should be the default behavior, but what do I know?
First thing you need to do is implement the UITextFieldDelegate in your UIViewController.

@interface MyViewController : UIViewController <UITextFieldDelegate> {

The next is to set the controller as the UITextField delegate (I do this in the viewDidLoad method).

- (void)viewDidLoad {

	[super viewDidLoad];

	[myTextField setDelegate:self];

Then, implement textFieldShouldReturn in your controller like this;
#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

	[textField resignFirstResponder];

	return YES;


The keyboard is the "first responder", and this causes it to go away when the "done" button is pressed (assuming you have a "done" button on your keyboard). Can anyone tell me why the numeric keypad doesn't have a done button??

iPhone development – tracking down uncaught exceptions

In the iPhone work I’ve been doing (my app), I’ve seen one error a number of times.. with various causes that were hard to track down. I’d see TERMINATED_DUE_TO_UNCAUGHT_EXCEPTION and never got a good stack trace. I found the solution in an iPhone dev forum (here) and thought I’d write this up to share the answer in case it saves someone some time.

What you need to do is set a breakpoint in objc_throw_exception. To do that, create a .gdbinit file in your home directory. Add the following to that file (I think the last line is the most important, but I have all of this in mine).

fb -[NSException raise]
fb -[_NSZombie release]
fb szone_error
fb objc_exception_throw

Then, bring up the debugger and run your app. Once you get an exception raised, the debugger stops where that exception is about to be thrown and you can see exactly where, in your code the problem originated! Big help to me, I can tell you! (Thanks,!)