使用 UITableView 和 NSOrderedSet 对核心数据进行排序 [英] Core Data ordering with a UITableView and NSOrderedSet

查看:21
本文介绍了使用 UITableView 和 NSOrderedSet 对核心数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Core Data 作为后备存储的 UITableViewController 中实现用户定义的排序需要执行哪些步骤?

What are the steps that I need to perform to implement user-defined ordering in a UITableViewController with Core Data as the backing store?

我还需要响应 -tableView:moveRowAtIndexPath:fromIndexPath:toIndexPath: 还是模型重新排序由表视图自动处理?我可以只选中 Core Data 模型文件中的Ordered"复选框并期望它将更改从 table view 传输到 store,还是我必须做更多?我是否必须更改 fetchedResultsController 获取其对象的方式(例如添加排序描述符)?

Do I still need to respond to -tableView:moveRowAtIndexPath:fromIndexPath:toIndexPath: or is the model re-ordering handled automatically by the table view? Can I just check the "Ordered" checkbox in the Core Data model file and expect it to transmit the changes from the table view to the store, or do I have to do more? Do I have to change the way my fetchedResultsController gets it's objects (e.g. add a sort descriptor)?

推荐答案

你不需要放弃 NSFetchedResultsController 或 NSOrderedSet.如果您坚持使用 NSOrderedSet,那么简单的方法就是向您的对象 NSManagedObject 子类添加一个方法.因此,例如,如果您有一个包含有序章节集的对象 Book,您可以向章节对象添加一个方法:

You don't need to abandon NSFetchedResultsController or NSOrderedSet. If you stick with NSOrderedSet, the easy way is to just add a method to your objects NSManagedObject subclass. So for instance, if you have an object Book with an ordered set of Chapters, you can add a method to the Chapters object:

- (NSUInteger)indexInBookChapters
{
    NSUInteger index = [self.book.chapters indexOfObject:self];
    return index;
}

提示:将此添加到一个类别中,这样它就不会被 CoreData 自动生成的代码覆盖.

Tip: Add this to a category so it doesn't get overwritten by CoreData auto generated code.

然后你可以在你的 NSFetchedResultsController 的排序描述符中使用这个方法:

Then you can use this method in your sort descriptor for your NSFetchedResultsController:

fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"indexInBookChapters" ascending:YES]];

这篇关于使用 UITableView 和 NSOrderedSet 对核心数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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