Search code examples
objective-cnstableview

Clear table using a button in objective-c


I'm trying to clear all from a table using a button. Basically reset the table. I use the following to remove one slice at a time but how do I clear all from the table? Thank you in advance!

- (IBAction)handleRemoveSliceTapped:(NSButton *)sender {
NSInteger selectedRow = [self.sliceTable selectedRow];
if (selectedRow < 0) {
    return;
}
if ([self.sliceTimes count] == 0)  {
    return;
}

NSIndexSet *removalSet = [NSIndexSet indexSetWithIndex:selectedRow];
[self.sliceTable removeRowsAtIndexes:removalSet withAnimation:NSTableViewAnimationSlideUp];
[self.sliceTimes removeObjectAtIndex:selectedRow];
[self.sliceTable reloadData];

Solution

  • If your NSTableViewDataSource numberOfRowsInTableView returns 0, the table will become empty.

    Therefore, you can just clear your view model, and reload the table:

    [self.sliceTimes removeAllObjects];
    [self.sliceTable reloadData];
    

    This is without animation. If you need the animation, include all row indexes in your NSIndexSet, and do the updates between beginUpdates/endUpdates (see https://developer.apple.com/documentation/appkit/nstableview/1527288-beginupdates?language=objc ):

    NSIndexSet *removalSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.sliceTimes.count)];
    [self.sliceTable beginUpdates];
    [self.sliceTable removeRowsAtIndexes:removalSet withAnimation:NSTableViewAnimationSlideUp];
    [self.sliceTimes removeAllObjects];
    [self.sliceTable endUpdates];