Graphics Programs Reference
In-Depth Information
To confirm that this exception will be thrown, let's return to where this
initWithNibName:bundle:
method is currently called - the
tableView:didSelectRowAtIndexPath:
method of
ItemsViewControl-
ler
. In this method,
ItemsViewController
creates an instance of
De-
tailViewController
and sends it the message
init
, which eventually calls
initWithNibName:bundle:
. Therefore, selecting a row in the table view will result
in the “Wrong initializer” exception being thrown.
Build and run the application and tap a row. You application will halt, and you will see an
exception in the console. Notice that the name and the reason are part of the console mes-
sage.
You don't want to see this exception again, so in
ItemsViewController.m
, update
tableView:didSelectRowAtIndexPath:
to use the new initializer.
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController =
[[DetailViewController alloc] init];
DetailViewController *detailViewController =
[[DetailViewController alloc] initForNewItem:NO];
NSArray *items = [[BNRItemStore sharedStore] allItems];
Build and run the application again. Nothing new and exciting will happen, but your ap-
plication will no longer crash when you select a row in the table.
Now that we've got our new initializer in place, let's change what happens when the user
adds a new item.
In
ItemsViewController.m
, edit the
addNewItem:
method to create an instance
of
DetailViewController
in a
UINavigationController
and present the
navigation controller modally.
- (IBAction)addNewItem:(id)sender
{
BNRItem *newItem = [[BNRItemStore sharedStore] createItem];
int lastRow = [[[BNRItemStore sharedStore] allItems] indexOfObject:newItem];
NSIndexPath *ip = [NSIndexPath indexPathForRow:lastRow inSection:0];
[[self tableView] insertRowsAtIndexPaths:[NSArray arrayWithObject:ip]
withRowAnimation:UITableViewRowAnimationTop];
DetailViewController *detailViewController =
[[DetailViewController alloc] initForNewItem:YES];
[detailViewController setItem:newItem];