views:

328

answers:

2

Apple's documentation implies that for a UITableView editable with an "Edit/Done" button, you should create and destroy the button each time it's toggled.

Here's a snippet of code "BonjourWeb" sample code project that does this:

if (editing) {
    // Add the "done" button to the navigation bar
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneAction:)];

    self.navigationItem.leftBarButtonItem = doneButton;
    [doneButton release];

    [self addAddButton:YES];
} else {
    if ([self.customs count]) {
        // Add the "edit" button to the navigation bar
        UIBarButtonItem *editButton = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editAction:)];

        self.navigationItem.leftBarButtonItem = editButton;
        [editButton release];
    }

Is this really better than just editing the title of the button? Is there some performance optimisation that I'm not seeing? Or is this just bad example source?

+1  A: 

There are multiple default UIBarButtonItems done by Apple. Using these default buttons, called UIBarButtonSystemItem, will enable the user to identify the action that this button does in every app that uses these. Apple requires to use these default buttons according to their HIGs.
So the answer comes down to this: Changing the title of the button is not the same as using the default "Done" and "Edit" buttons. These have a different look (the "Done" button for example is using a light blue).

bddckr
A: 

I don't know why they do that in that code sample, but there's a much easier way to add an Edit/Done button for any kind of view controller (available since SDK 2.0). UIViewController comes with its own edit button item, so you can just do this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = self.editButtonItem;
}

The edit button will take care of transitioning the view controller into and out of editing mode, and it will update the button style accordingly.

Brian