views:

1094

answers:

4

For a simple example of using a NSMutableArray of strings called rows, what do I have to implement in my table controller to move the tableView rows and have the changes reflected in my array?

+5  A: 

Here we do our heavy lifting.

 - (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]; 

    // remove the original from the data structure
    [rows removeObjectAtIndex:fromIndexPath.row];

    // insert the object at the target row
    [rows insertObject:r atIndex:toIndexPath.row];
    NSLog(@"result of move :\n%@", [self rows]);
}

Since this is a basic example, lets make all the rows moveable.

- (BOOL)tableView:(UITableView *)tableView 
canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
Ryan Townshend
When removeObjectAtIndex is called, will that reduce that object's reference count (and perhaps cause it to be deallocated)? I think exchangeObjectAtIndex:withObjectAtIndex: (as suggested by @dreamlax) is safer.
Kristopher Johnson
BTW, if you are answering your own question, I think it is good form to make it a wiki.
Kristopher Johnson
+2  A: 

NSMutableArray has a method called exchangeObjectAtIndex:withObjectAtIndex:.

dreamlax
I have tried this one, but the behavior is different. The table doesn't exchange the rows, it removes one row, then inserts it in a different location. If I use this method, the table and the backing store get more out out of sync with each move.
Ryan Townshend
A: 
WiZ
+2  A: 

According to Apple's documentation, and my own experience, this is some simple code that works quite well:

NSObject *tempObj = [[self.rows objectAtIndex:fromIndexPath.row] retain];
[self.rows removeObjectAtIndex:fromIndexPath.row];
[self.rows insertObject:tempObj atIndex:toIndexPath.row];
[tempObj release];
Michael Berding