使用 CoreData 和数组填充 Table 个视图部分

Populate Table View Sections with CoreData and Array

我想用一堆文件夹填充我的 Table 视图(类似于 Apple Notes 应用程序的文件夹结构屏幕)。我希望电视中的第一项是一个单元格,该单元格会导致其他文件夹中所有内容的组合。我可以显示所有文件夹,但在尝试找出如何显示 'combo contents' 文件夹时遇到问题。所有单独的文件夹都是在 CoreData 上创建的,并通过 NSFetchedResultsController 提供。

我创建了一个仅包含一个文件夹实例的数组,用作组合文件夹的对象。我有以下代码来尝试创建 2 个部分(1 个用于组合,另一个用于单个文件夹)但目前它只会显示我在案例 0 中放入的内容。我这样做是否正确?

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
    case 0:
        return comboFolder.count
    case 1:
        return fetchedRC.fetchedObjects?.count ?? 0
    default:
        return 0
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "folderCell", for: indexPath) as! FolderTableViewCell

    switch indexPath.section {
    case 0:
        let folder = comboFolder[indexPath.row]
        cell.updateComboFolder(with: folder)
    case 1:
        let folder = fetchedRC.object(at: indexPath)
        cell.update(with: folder)

    default:
        print("default")
    }
    return cell
 }

这是一个包含您的基本设置的示例项目 - https://github.com/nambatee/CombinedFolders1

诀窍是调整indexPath。您正在处理 2 个部分,但您的 NSFetchedResultsController 只知道 1 个部分。因此,您需要注意不要向 NSFetchedResultsController 索取索引 1 部分中的对象。