[英]How to get the latest objects from NSFetchedResultsController with a limit?
Maybe the title of question is not apriopriate, but here is what I need to achieve with my NSFetchedResultsController
: 也许问题的标题是不是apriopriate,但这里是我需要实现我的
NSFetchedResultsController
:
private func setupOnceFetchedResultsController() {
if fetchedResultsController == nil {
let context = NSManagedObjectContext.MR_defaultContext()
let fetchReguest = NSFetchRequest(entityName: "WLComment")
let createdAtDescriptor = NSSortDescriptor(key: "createdAt", ascending: true)
fetchReguest.predicate = NSPredicate(format: "item.identifier = %d", item.identifier)
fetchReguest.sortDescriptors = [createdAtDescriptor]
fetchReguest.fetchLimit = 10
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchReguest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
try! fetchedResultsController.performFetch()
tableView.reloadData()
}
}
Suppose I have about 100 comments. 假设我有100条评论。 The oldest on the top, and the latest on the bottom.
最旧的在顶部,最新的在底部。 There is no problem when I need to display all of them, but here I need only 10 of them.
当我需要显示所有它们时没有问题,但是在这里我只需要显示10个即可。 The above
NSFetchedResultsController
will display the first 10 of 100 messages, but I need to display the latest 10. 上面的
NSFetchedResultsController
将显示100条消息中的前10条,但是我需要显示最新的10条。
Is there a way to let it know what I need? 有没有办法让我知道我需要什么?
Depending on how you are going to use the data later on, you can choose from at least two options: 根据以后使用数据的方式,可以选择至少两个选项:
revert the sort descriptor, will return the end of the sorted list with reverted order; 还原排序描述符,将以还原顺序返回排序列表的末尾;
get the number of items first and set the appropriate fetchOffset
, will return the required number of items, ordered as needed. 首先获取项目数并设置适当的
fetchOffset
,将返回所需的项目数,并根据需要进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.