views:

106

answers:

3

Hi, I am trying to remove a the last uitablviewcell from a uitableview, but I am having some trouble. The code I have so far is.

[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[self.tableView numberOfRowsInSection:0]] withRowAnimation:NO];

Which I thought would remove the last cell? Any suggestions? Thanks.

+1  A: 

The number of rows in the section isn't 0 based (i.e. it would return 1 even though indexPath.row == 0). Try arrayWithObject:([self.tableView numberOfRowsInSection:0] - 1).

Also, [self.tableView numberOfRowsInSection:] returns a NSInteger, when the array really needs an NSIndexPath object.

refulgentis
+1  A: 

Assuming you only have 1 section in your table, this should do it, depending on where you'd put this code:

NSInteger temprowcount = [self.tableView numberOfRowsInSection:0];
if (temprowcount > 0) {
 [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:temprowcount-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
mjdth
A: 

If you have more than one section, assuming self is the view controller that contains tableView and conforms to the UITableViewDataSource protocol:

NSUInteger _lastSection = [self numberOfSectionsInTableView:tableView];
NSUInteger _lastRow = [tableView numberOfRowsInSection:_lastSection] - 1;
NSUInteger _path[2] = {_lastSection, _lastRow};
NSIndexPath *_indexPath = [[NSIndexPath alloc] initWithIndexes:_path length:2];
NSArray *_indexPaths = [[NSArray alloc] initWithObjects:_indexPath, nil];
[_indexPath release];

[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:_indexPaths withRowAnimation:UITableViewRowAnimationNone];
[tableView endUpdates];

[_indexPaths release];
Alex Reynolds