且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何实现 CoreData 记录的重新排序?

更新时间:2023-11-24 08:35:46

FetchedResultsController 及其委托不适用于用户驱动的模型更改.参见 Apple 参考文档.寻找用户驱动的更新部分.因此,如果您寻找某种神奇的单行方式,遗憾的是没有这样的方式.

FetchedResultsController and its delegate are not meant to be used for user-driven model changes. See the Apple reference doc. Look for User-Driven Updates part. So if you look for some magical, one-line way, there's not such, sadly.

您需要做的是在此方法中进行更新:

What you need to do is make updates in this method:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 userDrivenDataModelChange = YES;

 ...[UPDATE THE MODEL then SAVE CONTEXT]...

 userDrivenDataModelChange = NO;
}

并防止通知执行任何操作,因为用户已经完成了更改:

and also prevent the notifications to do anything, as changes are already done by the user:

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
 if (userDrivenDataModelChange) return;
 ...
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
 if (userDrivenDataModelChange) return;
 ...
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
 if (userDrivenDataModelChange) return;
 ...
}

我刚刚在我的待办事项应用 (Quickie) 中实现了这一点,并且运行良好.

I have just implemented this in my to-do app (Quickie) and it works fine.