如何实现 CoreData 记录的重新排序? [英] How to implement re-ordering of CoreData records?

查看:11
本文介绍了如何实现 CoreData 记录的重新排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 iPhone 应用程序中使用 CoreData,但 CoreData 不提供允许您重新排序记录的自动方式.我想使用另一列来存储订单信息,但是使用连续数字进行排序索引有问题.如果我处理大量数据,重新排序记录可能涉及更新排序信息上的大量记录(这有点像更改数组元素的顺序)

I am using CoreData for my iPhone app, but CoreData doesn't provide an automatic way of allowing you to reorder the records. I thought of using another column to store the order info, but using contiguous numbers for ordering index has a problem. if I am dealing with lots of data, reordering a record potentially involves updating a lot of records on the ordering info (it's sorta like changing the order of an array element)

实现高效订购方案的最佳方法是什么?

What's the best way to implement an efficient ordering scheme?

推荐答案

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.

这篇关于如何实现 CoreData 记录的重新排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆