views:

244

answers:

2

I have an Edit button in my navigation bar, and I have an table view.

My edit button calls an -editAction method.

And then, I have this piece of code to delete a cell, but I don't know how I can make the edit button to call this code...or how the edit button can let the table view display those red delete circles for every cell, which then trigger this:

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the managed object at the given index path
        NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
        [managedObjectContext deleteObject:eventToDelete];

        // Update Event objects array and table view
        [eventsArray removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

        // Commit the change
        NSError *error;
        if (![managedObjectContext save:&error]) {
            // Handle the error
        }
    } 
}
+2  A: 

According to the UITableView class reference docs, the code:

tableView.editing = YES;

Should put the table into editing mode and display those red delete circles. Then when the user deletes a cell your data source method should be called.

You can also use [tableView setEditing:YES animated:YES]; for an animated effect

cidered
+2  A: 

In your view controller's -viewDidLoad method add the Edit button:

self.navigationItem.rightBarButtonItem = self.editButtonItem;

This button will toggle the controller's editing mode, sending it -setEditing:animated:

Costique
Where does the editButtonItem come from? There is no such property in UITableView or UITableViewController, and in the entire example code no editButtonItem is defined either. Confusing...
openfrog
It's from category UIViewControllerEditing for UIViewController, see UIViewController.h.
Costique
Costique, this looks like a good answer, but is this specific to UITableViewController? Otherwise not sure how the UITableView gets the setEditing:animated: message? OP wasn't specific about view controller class, which is why I gave my answer but your answer would be preferable if this is the case. Thanks
cidered
UIViewControllerEditing protocol defines this method for any UIViewController, including UITableViewController and your own UIViewController subclasses: -(UIBarButtonItem *)editButtonItem. In other words, the standard Edit/Done button is provided for all view controllers absolutely for free. The button's target is set to the controller, its action is set to -setEditing: automatically. There's just no reason not to use it :)
Costique