【发布时间】:2010-11-12 11:39:06
【问题描述】:
我正在尝试找到一个代码示例,该示例显示了当单元格使用 fetchedResultsController(即与核心数据结合)时如何处理 tableView 中的移动/重新排列单元格。我收到了 moveRowAtIndexPath: 对我的数据源的调用,但我找不到正确的黑魔法组合来让表/数据正确识别更改。
例如,当我将第 0 行移到第 2 行然后放开时,它“看起来”是正确的。然后我点击“完成”。向上滑动以填充第 0 行的行 (1) 仍然具有其编辑模式外观(减号和移动图标),而下方的其他行则滑回正常外观。如果我向下滚动,当第 2 行(原来是 0,记得吗?)接近顶部时,它会完全消失。
WTF。我是否需要以某种方式使 fetchedResultsController 无效?每当我将其设置为零时,我都会崩溃。我应该释放它吗?我在杂草丛中吗?
这是我目前在里面得到的...
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
/*
Update the links data in response to the move.
Update the display order indexes within the range of the move.
*/
if (fromIndexPath.section == toIndexPath.section) {
NSInteger start = fromIndexPath.row;
NSInteger end = toIndexPath.row;
NSInteger i = 0;
if (toIndexPath.row < start)
start = toIndexPath.row;
if (fromIndexPath.row > end)
end = fromIndexPath.row;
for (i = start; i <= end; i++) {
NSIndexPath *tempPath = [NSIndexPath indexPathForRow:i inSection:toIndexPath.section];
LinkObj *link = [fetchedResultsController objectAtIndexPath:tempPath];
//[managedObjectContext deleteObject:[fetchedResultsController objectAtIndexPath:tempPath]];
link.order = [NSNumber numberWithInteger:i];
[managedObjectContext refreshObject:link mergeChanges:YES];
//[managedObjectContext insertObject:link];
}
}
// Save the context.
NSError *error;
if (![context save:&error]) {
// Handle the error...
}
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
if (self.theTableView != nil)
[self.theTableView beginUpdates];
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
if (self.theTableView != nil) {
[self.theTableView endUpdates];
}
}
【问题讨论】:
-
我的解决方法有点不同(测试时会发布)。为此真正需要的是“Reverse-NSFetchedResultsController”。本质上为 NSFetchedResultsController 提供 UITableView、排序顺序和节标题,然后让它将所有内容写回 CoreData。我想我可以试着把它放在一起玩。
-
绝对......比我的解决方案更优雅一点,它允许在存储的数据和表用户界面之间进行双向同步。我很想看看你完成后的想法。
-
对于它的价值,Matt Long 最近发布了一个关于重新排序 NSFetchedResultsController 支持的表中的行的好教程:cimgf.com/2010/06/05/re-ordering-nsfetchedresultscontroller
-
查看这个简单的解决方案:stackoverflow.com/a/15625897/308315
标签: iphone uitableview core-data