Deleting rows


#1

Just wanted to say that this is my first BNR book and I’m absolutely loving it. I come from a web background, and this is my first concerted foray into compiled programming (the Java dabbling I did a few years ago doesn’t really count in my mind). I can’t praise you guys enough. The teaching style in this book is superlative. I’m looking forward to getting my hands dirty with the iOS programming book once I’m done with this.

But anyway, to my question: I’ve successfully implemented a delete button which deletes the last row of the todo list. I’ve even put in a check warning the user if he’s trying to delete items from a list that doesn’t have anything in it. And it works well enough. Here’s the code:

[code]- (IBAction)deleteItem:(id)sender
{
// Check if there are any items to delete. If not, inform the user.
if (!toDoItems || [toDoItems count] == 0) {
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@“There is no field for you to delete.”];
[alert runModal];
}

// If there is an item, delete it, refresh the table view, and mark as unsaved.
[toDoItems removeLastObject];
[itemTableView reloadData];
[self updateChangeCount:NSChangeDone];

}[/code]

I’d like to, however, allow the user to delete the row that he’s selected for editing rather than deleting from the end of the array. I suspect this requires some extra wiring in Interface Builder, and the use of removeObjectAtIndex:? Can you point me in the right direction? Or is this too advanced for me at this early stage?

Thanks for any help/advice.

–Damir


#2

NSTableView has a method selectedRow, which will return the index of the currently selected row. (If no row is selected, it returns -1.)

(And thanks for the kind words. I really appreciate them.)


#3

Excellent, thanks—exactly what I was looking for! (Gotta learn to read that documentation more carefully…)


#4

I did this. Seems to work without any problems.

  • (IBAction)deleteItem:(id)sender
    {
    if ([itemTableView selectedRow] != -1) {

      [todoItems removeObjectAtIndex:[itemTableView selectedRow]];
      
      [itemTableView reloadData];
      
      [self updateChangeCount:NSChangeDone];
    

    }
    }