Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView delete all rows at once

How is it possible to delete all rows from UITableView at once? Because when I reload table view with new data, I am still inserting new rows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    CustomTableViewCell *cell = (CustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[CustomTableViewCell alloc] initWithFrame:CGRectZero] autorelease];
    }

    //... setting the new cell here ...

    return cell;
}

Thank you.

like image 963
Martin Pilch Avatar asked Jun 10 '11 21:06

Martin Pilch


People also ask

How to remove cell UITableView?

So, to remove a cell from a table view you first remove it from your data source, then you call deleteRows(at:) on your table view, providing it with an array of index paths that should be zapped. You can create index paths yourself, you just need a section and row number.


2 Answers

Do this.

Before you are reloading the table with

[tableView reloadData];

Remove all objects from your tableView array (The array which populated your tableView) For example.

[myArray removeAllObjects];
[tableView reloadData];
like image 136
Legolas Avatar answered Sep 28 '22 05:09

Legolas


FYI, The solution above "Delete all of your dataSource, then call reloadData." sounds like they are advocating this:

TableView.dataSource = nil;
[TableView reloadData];

I tried that and it seemed to work. Except, in iOS 8.1, I got random crashes. And I do mean random, as in, I could execute that code 10x and it would crash 1x. So, I used the recommended answer of:

[myArray removeAllObjects];
[tableView reloadData];

and now I am good.

like image 38
Chad Hine Avatar answered Sep 28 '22 06:09

Chad Hine