Deleting cell from a tableview - Error - Code prov

2019-09-06 01:57发布

问题:

I have a custom cell and i am adding a segment control to it.

-(void)segmentclicked:(id)sender{


        UISegmentedControl *segmentC = (UISegmentedControl *)sender;

        CustomCell *cell=(CustomCell *)segmentC.superview.superview;

        NSIndexPath *indexPath = [self.table indexPathForCell:cell];

        NSMutableArray *discardarr = [NSMutableArray array];

        [discardarr addObject:[self.entries objectAtIndex:indexPath.row]];

        [self.table beginUpdates];

        [self.itemsArray removeObjectsInArray:discardarr ]; 

        [self.table deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]  withRowAnimation:NO];         

        self.entries = [NSArray arrayWithArray:self.itemsArray];

        [self.table endUpdates];

        [self.table reloadData];


    }
}

I get the following error;

'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (10) must be equal to the number of rows contained in that section before the update (10), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

* First throw call stack:

1.) how could i get rid of this, i believe i have done everything accordingly. I have even tried adding the line [self.table reloadData]; above [self.table endUpdates]; , still there isn't any change. Help

回答1:

once you delete the rows in your code by this line [self.table deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:NO];

your tableview again checks with the datasource to see the number of sections in the row and the number of rows in the sections.. The error is because in that checking your deleted element still exists as a datasource element which the tableview should show but you have called delete that row.

For example.

in my number of rows i return 7 .

but if i delete a row i have to make this return 6..but your still might be 7..

(generally the return is some [array count] i have just used return 7 as an example)