使用 NSFetchedResultsController 排序时在多个部分中的一个对象

One object in multiple sections when sorting with NSFetchedResultsController

我刚开始使用 Core Data 和 NSFetchedResultsController,但有点卡住了。我有一个 Book 实体,它有一个 String 类型的类别属性。数据被加载到一个集合视图中,并根据该类别按部分分组。这样一切都很好,但问题是一本书应该能够出现在多个类别(和集合视图部分)中。我可以将类别的类型更改为字符串数组,但我该如何进行排序?

let request = Book.fetchedRequest() as NSFetchRequest<Book>
let categorySort = NSSortDescriptor(key: #keyPath(Book.category)), ascending:true)
request.sortDescriptors = [categorySort]

do {
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: #keyPath(Book.category)), cacheName: nil) 
try fetchedResultsController.performFetch()
} catch let error as NSError {
print(“Could not fetch. \(error), \(error.userInfo)”)
}

我应该放弃使用 NSFetchedResultsController 还是有可能使它起作用?

我认为将类别属性保留为字符串没有任何问题。只需改变处理书籍数组的方式即可。

创建一个类别数组,例如

var booksInCategories: [[Book]] = []

此变量将保存每个数组中一个类别中的所有书籍。假设您的书籍数组称为 books.

var books: [Book] = []

然后将每本书放在每个类别中,并将其添加到 booksInCatogories 对象中。假设您将所有类别作为另一个字符串数组。

var categories = ["Fiction", "Science", "Children", "Education"] // just an example

如果有 n 个类别,那么 booksInCatogories 中就有 n 个书籍数组。

for category in categories {
    var booksInCategory: [Book] = []
    for book in books {
        if book.category.range(of: category) != nil { // checks if category string contains particular category
            booksInCategory.append(book)
        }
    }
    if booksInCategory.count > 0 { // to exclude empty array if a category doesn't have any books under it
        booksInCategories.append(booksInCategory)
    }
}

您现在可以使用 booksInCategories 数组使用 booksInCategories 中的每个数组显示属于每个部分下每个类别的所有书籍。

... a Book should be able to appear in multiple categories (and collection view sections).

Should I just give up on using NSFetchedResultsController or is it possible to make this work?

您描述的内容无法通过获取的结果控制器实现。 NSFetchedResultsController 获取所有获取的对象(可能是 由谓词过滤),根据排序描述符对它们进行排序,以及 根据 sectionNameKeyPath 参数对它们进行分组。

获取的结果控制器不可能提供相同的对象 多次(在相同或不同的部分)。