Use of autorelease in didSelectRow method


#1

Here’s the code for the didSelectRowAtIndexPath method as it is written in the book:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ItemDetailViewController *detailViewController = [[[ItemDetailViewController alloc] init] autorelease];
    
    [[self navigationController] pushViewController:detailViewController animated:YES];
}

Why is autorelease used here instead of calling [detailViewController release] after pushing the view controller to the stack? I tried doing it this way, and it worked just fine. Is there a reason autorelease is used instead of a simple release?


#2

Either way works just fine. I would place the release statement after the push, personally. However minute, there is a performance cost to using autorelease. Getting into the habit of not using autorelease except when necessary is definitely good.

Note, this is irrelevant when using ARC starting with the release of iOS 5, as explicit calls to retain, release, autorelease, and dealloc are not allowed.