It is because you should have a dynamic way of returning the number of rows.
For example, I create an 3 arrays. Each with 3 values (these are NSArray variables) :
In .h file:
NSArray *firstArray;
NSArray *secondArray;
NSArray *thirdArray;
In .m file, viewDidLoad or init or something similar:
firstArray = [NSArray arrayWithObjects:@"Cat", @"Mouse", @"Dog", nil];
secondArray = [NSArray arrayWithObjects:@"Plane", @"Car", @"Truck", nil];
thirdArray = [NSArray arrayWithObjects:@"Bread", @"Peanuts", @"Ham", nil];
When returning number of rows in table, I have :
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return array.count;
if (section == 0) {
return firstArray.count;
} else if (section == 1) {
return secondArray.count;
} else {
return thirdArray.count;
}
}
Then, in cellForRow :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
if (indexPath.section == 0) {
cell.textLabel.text = [firstArray objectAtIndex:indexPath.row];
} else if (indexPath.section == 1) {
cell.textLabel.text = [secondArray objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [thirdArray objectAtIndex:indexPath.row];
}
return cell;
}
Then I delete @"Dog" by swiping on the table or some other way you want to delete. Then, when reloading the table, your array count will be 2, so the table will "know" that it has to display only 2 rows. Basically, you need to update your data source as well.
It applies for the other sections as well. Because you remove elements from arrays, number of rows will be updated also.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionreturns the right number of rows before and after the deletion. - CainaSouza