Mattias Farnemyhr
Mattias Farnemyhr

Reputation: 4238

Moving a row between sections

I have a problem with my moveRowAtIndexPath:toIndexPath code.

It works fine when I'm moving cells within a section but when I try to move a row from one section (say from indexPath [1,1] to indexPath [2,0]) to another I get a crash with this error message:

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

Here is my code, again, it works fine if the two indexPaths share the same section number:

- (void)moveRowAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath
{
    NSMutableArray *cells = [[self cellsAtSectionOfIndexPath:indexPath] mutableCopy];
    Cell *cell = [self dataAtIndexPath:indexPath];
    Cell *newCell = [self dataAtIndexPath:newIndexPath];

    if ([indexPath section] == [newIndexPath section])
    {
        [cells replaceObjectAtIndex:indexPath.row withObject:newCell];
        [cells replaceObjectAtIndex:newIndexPath.row withObject:cell];
        [self replaceCellsAtIndexPath:indexPath withCells:cells];
    }
    else
    {
        NSMutableArray *newCells = [[self cellsAtSectionOfIndexPath:newIndexPath] mutableCopy];
        [cells replaceObjectAtIndex:indexPath.row withObject:newCell];
        [newCells replaceObjectAtIndex:newIndexPath.row withObject:cell];
        [self replaceCellsAtIndexPath:indexPath withCells:cells];
        [self replaceCellsAtIndexPath:newIndexPath withCells:newCells];
    }

    [super moveRowAtIndexPath:indexPath toIndexPath:newIndexPath];
}

How can I fix this?

Upvotes: 0

Views: 903

Answers (1)

Levi
Levi

Reputation: 7343

The problem is with your data source. The error means that you are removing a row from a section but the numberOfRowsInSection: method returns the same number when it should return the old number minus 1. Same thing with adding the row to the other section.

Upvotes: 2

Related Questions