ozking
ozking

Reputation: 448

Objective c - Deleting rows of a table view

it's my first question in this awesome site. I've really searched a lot and yet find an answer to the next problem.

I have a table view with 9 cells. One of the cells has a switch button in it. When the switched button value changes, i want to delete 2 rows of the table view. I have written the next code:

- (IBAction)switchValueChanged:(id)sender {
NSLog(@"%@", ([switch isOn]) ? @"ON" : @"OFF"); 

NSArray *deleteIndexPaths = [NSArray arrayWithObjects:
                             [NSIndexPath indexPathForRow:1 inSection:0],
                             [NSIndexPath indexPathForRow:2 inSection:0],
                             nil];

UITableView *tableView = (UITableView *)self.view;

[tableView beginUpdates];

[tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
// I Have to change the number of rows in the section here.

[tableView endUpdates];
}

When i run this, I'm getting a problem relating to the number of rows in the section - this number has been changed so i need to change it. I really can't find how i change it, but i know where i have to change it (see code).

How can i do it? how can i call the method numberOfRowsInSection:NSInteger and set also the rows?

Thank you very much :)

Upvotes: 1

Views: 4664

Answers (3)

dbgrman
dbgrman

Reputation: 5681

You have to also delete the data from the datasource of the table view. The data source is any container that holds the actual data which is being displayed on the table view. Just deleting the row only deletes the visual item of the row, when tableview is reloaded - it will want to draw 9-2 rows....but since number of rows is still returning 9, it will throw an inconsistency exception and tell you why. See the log carefully.

Upvotes: 0

deanWombourne
deanWombourne

Reputation: 38475

The number of rows in the table is in your

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

You need this to match the new number of rows in the table

---- EDIT

This means that you will need to keep track of the number of rows in your table.

Start with this set to 9 and delete 2 every time you change the switch

- (IBAction)switchValueChanged:(id)sender {
  NSLog(@"%@", ([switch isOn]) ? @"ON" : @"OFF");

  // We are going to delete 2 rows
  numberOfRows -= 2;
  ...

and in your numberOfRowsInSection instead of returning 9 each time, return the new number of rows

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return numberOfRows;
}

Upvotes: 2

alinoz
alinoz

Reputation: 2822

You should delete the data from the datasource not the table cells and then just to refresh the table view. At least this is how i would do the design.

Upvotes: 0

Related Questions