我在编辑模式下重新排列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问题的人太棒了!:)提前感谢!!!
-更新-
我发现,当我向上移动单元格时,该方法会不断引用同一个对象并将其更新为新的顺序,而不是用新的顺序更新下一个对象。
即。向上移动单元格-结果=(Object1.order=1,Object1.order=2,Object1.order=3)
即。向下移动单元格-结果=(Object1.order=1,Object2.order=2,Object3.order=0)
更改
for (NSInteger i=lowerIndexPath.row; i<=higherIndexPath.row; i++)
至
for (NSInteger i=fromIndexPath.row; i<=toIndexPath.row; i -= moveDirection)
在尝试了很多事情之后,我又回到了apple-docs的方法。对于其他和我有同样问题的人,请创建一个从coreData中获得的NSArray的可变副本,并使用apple-docs从索引中插入和删除。它似乎为我解决了问题
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html