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?
views:
1094answers:
4
+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
2009-01-28 02:45:44
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
2009-01-28 04:34:10
BTW, if you are answering your own question, I think it is good form to make it a wiki.
Kristopher Johnson
2009-01-28 04:34:55
+2
A:
NSMutableArray
has a method called exchangeObjectAtIndex:withObjectAtIndex:
.
dreamlax
2009-01-28 02:50:33
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
2009-01-28 14:00:39
A:
WiZ
2009-07-18 21:20:04
+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
2009-10-28 12:41:53