Monday, January 18, 2010

UITableViewController subclassing in XCode has incorrect stub

If you've ever tried to create a UITableViewController subclass using XCode with SDK 3.x (3.1.2 at the time of this writing), it is important to note that the commented out code in the didSelectRowAtIndexPath method is incorrect.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //Navigation logic may go here. Create and push another view controller.
AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
[self.navigationController pushViewController:anotherViewController];
[anotherViewController release];
}

If you try to modify the above code to use one of your own custom view controllers, you will see a compilation warning stating:

  'UINavigationController' may not respond to '-pushViewController:'

If you actually try to run your application and select an item which tries to push an additional view controller, an exception will be thrown that states:

  [NSObject doesNotRecognizeSelector:]

The exception is definitely very misleading. The reason for both of the above problems is a second required parameter for this call, as follows:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //Navigation logic may go here. Create and push another view controller.
AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
[anotherViewController release];
}

No comments:

Post a Comment