我正在尝试使用Core Data和NSFetchResutlController
来制作可扩展的表格单元格,但似乎Core Data不能有空部分!
(在点击标题视图时隐藏单元格。)
我的问题: 如果对于任何节行计数,我都返回0,则会出现错误!
这是我的实体:
ToDo
和Category
ToDo
与Category
具有一对一关系
Category
与ToDo
一对多关系
它们都有一个名为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
}