Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Neither of the above will work. In the original posted code, the tableview will crash because it removes the data that will still be in use, and even after that was corrected, The array would not have the correct data due to the way table does a 'rearrange'.</p> <p>exchangeObjectAtIndex:withObjectAtIndex: will not work for rearranging an array according to how a tableview implements its own rearranging</p> <p>Why? Because when the user selects a table cell to rearrange it, that cell does NOT get swapped with the cell they are moving it to. The cell they selected gets inserted at the new row index and then the original cell is removed. At least that's the way it appears to the user.</p> <p>Solution: Due to the way the tableview implements a rearrange, we need to perform a check to make sure we add and remove the right row. This code I put together is simple and works perfect for me. </p> <p>Using the original posted code data as an example:</p> <pre><code> - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { NSLog(@"move from:%d to:%d", fromIndexPath.row, toIndexPath.row); // fetch the object at the row being moved NSString *r = [rows objectAtIndex:fromIndexPath.row]; // checks to make sure we add and remove the right rows if (fromIndexPath.row &gt toIndexPath.row) { // insert the object at the target row [rows insertObject:r atIndex:toIndexPath.row]; // remove the original from the data structure [rows removeObjectAtIndex:(fromIndexPath.row + 1)]; } else if (fromIndexPath.row &lt toIndexPath.row) { // insert the object at the target row [rows insertObject:r atIndex:(toIndexPath.row + 1)]; // remove the original from the data structure [rows removeObjectAtIndex:(fromIndexPath.row)]; } } </code></pre> <p>If you take a few moments and take a look at what happens to a tableview during a rearrange you will understand why we add the 1's where we did.</p> <p>I'm pretty new to xcode, so I know there is probably an easier way to do this, or the code can probably be simplified....Just trying to help out where I can because it's taken me a few hours to figure this out. Hope this saves someone some time!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload