对于使用称为行的字符串的 NSMutableArray 的简单示例,我必须在表控制器中实现什么才能移动 tableView 行并将更改反映在我的数组中?
5 回答
在这里,我们进行繁重的工作。
- (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]);
}
由于这是一个基本示例,因此让所有行都可移动。
- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
以上都行不通。在原始发布的代码中,tableview 将崩溃,因为它删除了仍在使用的数据,即使在更正之后,由于 table 执行“重新排列”的方式,数组也不会包含正确的数据。
exchangeObjectAtIndex:withObjectAtIndex: 不适用于根据 tableview 如何实现自己的重新排列来重新排列数组
为什么?因为当用户选择一个表格单元格来重新排列它时,该单元格不会与他们将其移动到的单元格交换。他们选择的单元格被插入到新的行索引处,然后原始单元格被删除。至少在用户看来是这样的。
解决方案:由于 tableview 实现重新排列的方式,我们需要执行检查以确保添加和删除正确的行。我放在一起的这段代码很简单,对我来说很完美。
以原始贴出的代码数据为例:
- (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 > 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 < 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)];
}
}
如果你花点时间看看在重新排列期间 tableview 发生了什么,你就会明白为什么我们在我们做的地方添加 1。
我对 xcode 很陌生,所以我知道可能有一种更简单的方法可以做到这一点,或者代码可能可以简化......只是想尽我所能提供帮助,因为我花了几个小时才弄清楚这一点出去。希望这可以节省一些时间!
根据 Apple 的文档和我自己的经验,这是一些运行良好的简单代码:
NSObject *tempObj = [[self.rows objectAtIndex:fromIndexPath.row] retain];
[self.rows removeObjectAtIndex:fromIndexPath.row];
[self.rows insertObject:tempObj atIndex:toIndexPath.row];
[tempObj release];
NSMutableArray
有一个方法叫做exchangeObjectAtIndex:withObjectAtIndex:
.
在打破我的头脑反对一个简单的实现之后发现了这个讨论......迈克尔伯丁解决方案对我来说是最好的,苹果的方式,只记得在使用 ARC 时删除保留和释放。所以,一个更简洁的解决方案
NSObject *tempObj = [self.rows objectAtIndex:fromIndexPath.row];
[self.rows removeObjectAtIndex:fromIndexPath.row];
[self.rows insertObject:tempObj atIndex:toIndexPath.row];