具有核心数据的可扩展tableview单元格

时间:2019-12-10 15:23:07

标签: ios swift uitableview core-data

我正在尝试使用Core Data和NSFetchResutlController来制作可扩展的表格单元格,但似乎Core Data不能有空部分! (在点击标题视图时隐藏单元格。)

我的问题: 如果对于任何节行计数,我都返回0,则会出现错误!

这是我的实体:

ToDoCategory

ToDoCategory具有一对一关系 CategoryToDo一对多关系

它们都有一个名为name的属性String

这是我的代码:
FetchedResultsController:

lazy var fetchResultController: NSFetchedResultsController<ToDo> = {
    let fetchRequest: NSFetchRequest< ToDo > = ToDo.fetchRequest()
    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: #keyPath(ToDo.category.name), ascending: false),
        NSSortDescriptor(key: #keyPath(ToDo.name), ascending: false)
        ]
    let fetchRC = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.stack.managedContext, sectionNameKeyPath: #keyPath(ToDo.category.name), cacheName: nil)
    fetchRC.delegate = self

    return fetchRC
}()

TableView数据源:

func numberOfSections(in tableView: UITableView) -> Int {
    guard let sections = fetchResultController.sections else{return 0}
    return sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    guard let section = fetchResultController.sections?[section] else{return 0}
    return section.numberOfObjects
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
    let toDo = fetchResultController.object(at: indexPath)

    cell.textLabel?.text = toDo.name

    return cell
}

TableView委托

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderID") as! HeaderView
    guard let todo = fetchResultController.fetchedObjects?[section] else{return UIView()}

    view.lbl.text = todo.category?.name

    return view
}

0 个答案:

没有答案