如何使用NSFetchedResultsController在表视图控制器中添加一个部分(带有自定义标题单元格)?

时间:2015-08-06 08:34:19

标签: ios swift uitableview nsfetchedresultscontroller

我正在创建一个包含可扩展表的表视图,其中节(束)是自定义UITableViewCell以及行(伙伴) - 您可以制作任意一群朋友。我还使用NSFetchedResultsController填充表,我已经成功完成了。我遇到的困难是在向核心数据添加一堆时,NSFetchedResultsController会抛出此异常:

  

CoreData:错误:严重的应用程序错误。抓住了一个例外   在调用期间来自NSFetchedResultsController的委托   -controllerDidChangeContent :.尝试将第0行插入第1部分,但在使用userInfo更新后第1部分中只有0行   (空)

我希望能够添加一组(在模式对话框中)并让它自动显示在表视图中(根据NSFetchedResultController功能),但它会引发异常(尽管不会崩溃)如上所示,该部分未添加。

以下是NSFetchedResultsController的代码:

初始化(在加载表格视图时初始化)

lazy var fetchedResultsController: NSFetchedResultsController = {
    let bunchesFetchRequest = NSFetchRequest(entityName: Constants.CoreData.bunch)
    // Sort bunches by bunch name, in alphabetical order, not caring about capitalization
    let primarySortDescriptor = NSSortDescriptor(key: Constants.CoreData.Bunch.name, ascending: true, selector: "caseInsensitiveCompare:")
    bunchesFetchRequest.sortDescriptors = [primarySortDescriptor]

    // TODO: Answer question: Do we need this, does this benefit us at all, and how does prefetching work?
    bunchesFetchRequest.relationshipKeyPathsForPrefetching = [Constants.CoreData.Bunch.buddies]

    let frc = NSFetchedResultsController(
        fetchRequest: bunchesFetchRequest,
        managedObjectContext: CoreDataStackManager.sharedInstance().managedObjectContext!,
        sectionNameKeyPath: Constants.CoreData.Bunch.name,
        cacheName: nil
    )
    frc.delegate = self
    return frc
}()

表格查看方法

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // sections are the bunches
    if let sections = fetchedResultsController.sections {
        return sections.count
    }
    return 0
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // sections are the bunches (this is for when sectionNameKeyPath is set)
    if let sections = fetchedResultsController.sections {
        let currentSection = sections[section] as! NSFetchedResultsSectionInfo
        let bunch = currentSection.objects[0] as! Bunch
        // Return the number of buddies in this section (bunch)
        return bunch.buddies.count
    }
    return 0
}


func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    if let sections = fetchedResultsController.sections {
        let currentSection = sections[section] as! NSFetchedResultsSectionInfo
        let bunch = currentSection.objects[0] as! Bunch
            // Create BunchTableViewCell
        let headerCell: BunchTableViewCell = tableView.dequeueReusableCellWithIdentifier(bunchCellIdentifier) as! BunchTableViewCell

        headerCell.bunchNameLabel.text = bunch.name    
        return headerCell
    }
    return nil
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: BuddyInBunchTableViewCell = tableView.dequeueReusableCellWithIdentifier(buddyInBunchCellIdentifier, forIndexPath: indexPath) as! BuddyInBunchTableViewCell

    if let sections = fetchedResultsController.sections {
        let currentSection = sections[indexPath.section] as! NSFetchedResultsSectionInfo
        let bunch = currentSection.objects[0] as! Bunch
        let buddy: Buddy = bunch.getBuddiesInBunch()[indexPath.row]
        cell.buddyFullNameLabel.text = buddy.getFullName()
    }
    return cell
}

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 50.0 
}

NSFetchedResultsController方法

func controllerWillChangeContent(controller: NSFetchedResultsController) {
    self.tableView.beginUpdates()
}

func controller(
    controller: NSFetchedResultsController,
    didChangeObject anObject: AnyObject,
    atIndexPath indexPath: NSIndexPath?,
    forChangeType type: NSFetchedResultsChangeType,
    newIndexPath: NSIndexPath?) {

        switch type {
        case NSFetchedResultsChangeType.Insert:
            // Note that for Insert, we insert a row at the __newIndexPath__
            if let insertIndexPath = newIndexPath {
                // AAAAAAAAAA
                self.tableView.insertRowsAtIndexPaths([insertIndexPath], withRowAnimation: UITableViewRowAnimation.Fade)
                // BBBBBBBBBB
                // self.tableView.insertSections(NSIndexSet(index: insertIndexPath.section), withRowAnimation: UITableViewRowAnimation.Fade)
            }
        case NSFetchedResultsChangeType.Delete:
            // Note that for Delete, we delete the row at __indexPath__
            if let deleteIndexPath = indexPath {
                self.tableView.deleteRowsAtIndexPaths([deleteIndexPath], withRowAnimation: UITableViewRowAnimation.Fade)
            }
        case NSFetchedResultsChangeType.Update:
            // Note that for Update, we update the row at __indexPath__
            // Not yet implemented
            break
        case NSFetchedResultsChangeType.Move:
            // Note that for Move, we delete the row at __indexPath__
            if let deleteIndexPath = indexPath {
                self.tableView.deleteRowsAtIndexPaths([deleteIndexPath], withRowAnimation: UITableViewRowAnimation.Fade)
            }

            // Note that for Move, we insert a row at the __newIndexPath__
            if let insertIndexPath = newIndexPath {
                self.tableView.insertRowsAtIndexPaths([insertIndexPath], withRowAnimation: UITableViewRowAnimation.Fade)
            }
        }
}


func controller(
    controller: NSFetchedResultsController,
    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
    atIndex sectionIndex: Int,
    forChangeType type: NSFetchedResultsChangeType) {

        switch type {
        case .Insert:
            // AAAAAAAAAA
            let sectionIndexSet = NSIndexSet(index: sectionIndex)
            self.tableView.insertSections(sectionIndexSet, withRowAnimation: UITableViewRowAnimation.Fade)
            // BBBBBBBBBBB
            // break
        case .Delete:
            let sectionIndexSet = NSIndexSet(index: sectionIndex)
            self.tableView.deleteSections(sectionIndexSet, withRowAnimation: UITableViewRowAnimation.Fade)
        default:
            break
        }
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
    self.tableView.endUpdates()
}

注意:如果我在 AAAAAAAAAA 下注释掉这些行并取消注释 BBBBBBBBBB 中的行,我可以看到该单元格显示非常简短,但随后插入了下面的每个单元格单元格消失,我多次得到此错误:

  

没有重复使用表格单元格的索引路径

感谢任何帮助/建议!

1 个答案:

答案 0 :(得分:0)

好吧,我发现了:

" NSFetchedResultsController的一个更大问题是它无法显示空白部分。"

this blog post中提到了提及解决问题的方法(注意:我还没有实现它,但我现在知道以直观的方式不可能实现)。