Graphics Programs Reference
In-Depth Information
Adding Rows
There are a number of ways to add rows to a table view at runtime. The built-in behavior
for adding a row is to display a new row with a green plus sign icon. However, this tech-
nique has fallen out of favor because it's cumbersome to enter editing mode and then find
the row with the plus sign icon - especially in large tables.
So we're going to use the
New
button in the header view instead. When this button is
tapped, a new row will be added to the
UITableView
. In
ItemsViewControl-
ler.m
, implement
addNewItem:
.
- (IBAction)addNewItem:(id)sender
{
// Make a new index path for the 0th section, last row
int lastRow = [[self tableView] numberOfRowsInSection:0];
NSIndexPath *ip = [NSIndexPath indexPathForRow:lastRow inSection:0];
// Insert this new row into the table.
[[self tableView] insertRowsAtIndexPaths:[NSArray arrayWithObject:ip]
withRowAnimation:UITableViewRowAnimationTop];
}
Build and run the application. Tap the
New
button and... the application crashes. The con-
sole tells us that the table view has an internal inconsistency exception.
Remember that, ultimately, it is the
dataSource
of the
UITableView
that determines
the number of rows the table view should display. After inserting a new row, the table view
has six rows (the original five plus the new one). Then, it runs back to its
dataSource
and asks it for the number of rows it should be displaying.
ItemsViewController
consults the store and returns that there should be five rows. The
UITableView
then
says, “Hey, that's not right!” and throws an exception.
You must make sure that the
UITableView
and its
dataSource
agree on the number
of rows. Thus, you must also add a new
BNRItem
to the
BNRItemStore
before you in-
sert the new row. Update
addNewItem:
in
ItemsViewController.m
.
- (IBAction)addNewItem:(id)sender
{
int lastRow = [[self tableView] numberOfRowsInSection:0];
// Create a new BNRItem and add it to the store
BNRItem *newItem = [[BNRItemStore sharedStore] createItem];
// Figure out where that item is in the array
int lastRow = [[[BNRItemStore sharedStore] allItems] indexOfObject:newItem];
NSIndexPath *ip = [NSIndexPath indexPathForRow:lastRow inSection:0];