To change the order of rows in a UITableView, you will use another method from the UITableViewDataSource protocol – tableView:moveRowAtIndexPath:toIndexPath:.
To delete a row, you had to send the message deleteRowsAtIndexPaths:withRowAnimation: to the UITableView to confirm the deletion. Moving a row, however, doesn’t require confirmation; the table view moves the row on its own authority and sends the data source the message tableView:moveRowAtIndexPath:toIndexPath: to report the move. You just have to catch this message to update your data source to match the new order.
But before we can implement the data source method, we need to give the PossessionStore a method to change the order of Possessions in its allPossessions array. In PossessionStore.h, declare this method.
- (void)movePossessionAtIndex:(int)from toIndex:(int)to;
Implement this method in PossessionStore.m.
- (void)movePossessionAtIndex:(int)from toIndex:(int)to { if (from == to) { return; } // Get pointer to object being moved Possession *p = [allPossessions objectAtIndex:from]; // Retain it... (retain count of p = 2) [p retain]; // Remove p from array, it is automatically sent release (retain count of p = 1) [allPossessions removeObjectAtIndex:from]; // Insert p in array at new location, retained by array (retain count of p = 2) [allPossessions insertObject:p atIndex:to]; // Release p (retain count = 1, only owner is now array) [p release]; }
Now in ItemsViewController.m, implement tableView:moveRowAtIndexPath:toIndexPath: to update the store.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { [[PossessionStore defaultStore] movePossessionAtIndex:[fromIndexPath row] toIndex:[toIndexPath row]]; }
Build and run your application. Check out the new reordering controls (the three horizontal lines) on the side of each row. Touch and hold a reordering control and move the row to a new position (Figure 11.8).
Note that simply implementing tableView:moveRowAtIndexPath:toIndexPath: caused the reordering controls to appear. This is because Objective-C is a very smart language. The UITableView can ask its data source at runtime whether it implements tableView:moveRowAtIndexPath:toIndexPath:. If it does, the table view says, “Good, you can handle moving rows. I’ll add the re-ordering controls.” If not, it says, “You bum. If you are too lazy to implement that method, I’m not putting controls there.”
3.139.97.53