Jonnny
Jonnny

Reputation: 5039

Invalid Update when re-ordering rows across sections

I am trying to update my model when reordering some UITableViewCells across sections but getting the error:

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, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 1 moved out).

I have the following code, where I thought I was deleting and inserting rows correctly?? (but obviously not ;-) )

    // Update the data model according to edit actions delete or insert.
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
    let fromIndexPath = NSIndexPath(forRow: indexPath.row, inSection: indexPath.section)

    if editingStyle == UITableViewCellEditingStyle.Delete{
        playingList.removeAtIndex(fromIndexPath.row);
    }
}

    // Process the row move. This means updating the data model to correct the item indices.
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
{
    let moveFrom = NSIndexPath(forRow: sourceIndexPath.row, inSection: sourceIndexPath.section)
    let moveTo = NSIndexPath(forRow: destinationIndexPath.row, inSection: destinationIndexPath.section)

    // swap the data between the 2 arrays
    let dataPiece = playingList[moveFrom.section][moveFrom.row]
    playingList[moveTo.section].insert(dataPiece, atIndex: moveTo.row)
    playingList[moveFrom.section].removeAtIndex(moveFrom.row)
    // Do the move between the table view rows
    playerTableView.moveRowAtIndexPath(moveFrom, toIndexPath: moveTo)
}

Upvotes: 0

Views: 49

Answers (1)

rmaddy
rmaddy

Reputation: 318954

Your issue is that you are calling moveRowAtIndexPath. Just update your data model and you are done.

func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
{
    let moveFrom = NSIndexPath(forRow: sourceIndexPath.row, inSection: sourceIndexPath.section)
    let moveTo = NSIndexPath(forRow: destinationIndexPath.row, inSection: destinationIndexPath.section)

    // swap the data between the 2 arrays
    let dataPiece = playingList[moveFrom.section][moveFrom.row]
    playingList[moveTo.section].insert(dataPiece, atIndex: moveTo.row)
    playingList[moveFrom.section].removeAtIndex(moveFrom.row)
}

BTW - your commitEditStyle method is incorrect too. It is deleting the data for a whole section (but using the row instead of section). Just remove the one row:

playingList[indexPath.section].removeAtIndex(indexPath.row)

Upvotes: 1

Related Questions