我在编辑模式下重新排列 tableView 中的单元格时遇到问题。向下移动单元格可以正常工作,但向上移动单元格会对订单造成严重破坏。有时它会回到正常位置,有时它会选择一个随机点结束。具有讽刺意味的是,Core 数据模型和顺序每次都正确结束。
我搜索了STO,确实没有找到解决方案。
- 没有应用手势控制,我也尝试过禁用它们。
-尝试 [self setSuspendAutomaticTrackingOfChangesInManagedObjectContext:NO];
- 试过 [self.tableView.canCancelContentTouches = NO];
-NSFetchControls/delegates 被 BOOL 绕过
我用来移动单元格的代码与以下基本相同:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[_tableView setEditing:editing animated:animated];
if(editing) {
NSInteger rowsInSection = [self tableView:_tableView numberOfRowsInSection:0];
// Update the position of all items
for (NSInteger i=0; i<rowsInSection; i++) {
NSIndexPath *curIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
SomeManagedObject *curObj = [_fetchedResultsController objectAtIndexPath:curIndexPath];
NSNumber *newPosition = [NSNumber numberWithInteger:i];
if (![curObj.displayOrder isEqualToNumber:newPosition]) {
curObj.displayOrder = newPosition;
}
}
}
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSInteger moveDirection = 1;
NSIndexPath *lowerIndexPath = toIndexPath;
NSIndexPath *higherIndexPath = fromIndexPath;
if (fromIndexPath.row < toIndexPath.row) {
// Move items one position upwards
moveDirection = -1;
lowerIndexPath = fromIndexPath;
higherIndexPath = toIndexPath;
}
// Move all items between fromIndexPath and toIndexPath upwards or downwards by one position
for (NSInteger i=lowerIndexPath.row; i<=higherIndexPath.row; i++) {
NSIndexPath *curIndexPath = [NSIndexPath indexPathForRow:i inSection:fromIndexPath.section];
SomeManagedObject *curObj = [_fetchedResultsController objectAtIndexPath:curIndexPath];
NSNumber *newPosition = [NSNumber numberWithInteger:i+moveDirection];
curObj.displayOrder = newPosition;
}
SomeManagedObject *movedObj = [_fetchedResultsController objectAtIndexPath:fromIndexPath];
movedObj.displayOrder = [NSNumber numberWithInteger:toIndexPath.row];
NSError *error;
if (![_fetchedResultsController.managedObjectContext save:&error]) {
NSLog(@"Could not save context: %@", error);
} else {
[self.tableview reloadData];
}
}
希望有人能回答这个问题,因为回答 STO 问题的人真是太棒了!:) 提前致谢!!!
-更新-
我发现当我向上移动单元格时,该方法会一直引用同一个对象并将其更新为新顺序,而不是使用新顺序更新下一个对象。
IE。向上移动单元格 - 结果 = (Object1.order = 1, Object1.order = 2, Object1.order = 3)
IE。向下移动单元格 - 结果 = (Object1.order = 1, Object2.order = 2, Object3.order = 0)