使用 1 个 NSFetchedResultsController 的不同顺序的多个部分

multiple sections with different order using 1 NSFetchedResultsController

我有一个包含两个部分的表格视图,"favorite" 和 "recent" 用于订购存储的联系人。 我想按字母顺序对最喜欢的内容进行排序,并按日期对最近的内容进行排序。 每个联系人都有一个 "name" 和一个 "createdAt" 值(如果是收藏夹,则还有一个值 "favorite")。

使用下面的排序,我的部分 "favorite" 和 "recent" 具有正确的单元格,但都按字母顺序排序。

...
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "favorite", ascending: false),
                                    NSSortDescriptor(key: "firstName", ascending: true)]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: stack.viewContext, sectionNameKeyPath: "favorite", cacheName: nil)
...

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    guard let currentSection = fetchedResultsController.sections?[section] else { return nil }

    if currentSection.name == "0" {
        return "Recent".localized
    } else {
        return "Favorites".localized
    }
}

如何按日期对 "recent" 部分进行排序?

我通过手动更改第二部分的indexPath 解决了它。 我有一个函数 return indexPath 对第二部分的排序不同。

func changeIndexPath (_ indexPath: IndexPath) -> IndexPath {
... //sort you want
}

然后就可以使用tableview的功能了

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
newIndexPath = changeIndexPath(indexPath)
...
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
...
}
etc