在Swift中添加部分,NSFetchedResultsController时发现nil

时间:2016-05-05 20:23:03

标签: xcode swift uitableview nsfetchedresultscontroller

所以,我有一个FetchedResultsController,用户可以在其中将行添加到tableView中。根据用户添加行时tableView应该创建的部分的日期。例如,如果您在某一天添加​​一行,则其上方的部分应显示您添加的日期,如果您在第二天添加一行,该部分应显示该日期,依此类推。

问题在于,当我添加一行时,应用程序崩溃并说:“致命错误:在解开可选值时意外发现nil”

我也知道这是与部分相关的代码导致错误的事实,因为我可以在开始使用部分之前完美地添加行。

这是引起我提到的错误的行:

 self.foodTableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)

以下是用作sectionNameKeyPath的代码,其中变量“dater”是我的核心数据实体中“Date”类型的属性:

var formattedDateDue: String {
    get {

        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = .ShortStyle
        dateFormatter.timeStyle = .NoStyle
        return dateFormatter.stringFromDate(dater!)
    }
}

其他部分相关代码:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return self.fetchedResultsController.sections?.count ?? 0

func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
    switch type {
    case .Insert:
        //ERROR ON THIS LINE
        self.foodTableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
    case .Delete:
        self.foodTableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
    default:
        return
    }
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {



    if let sections = fetchedResultsController.sections {
        let currentSection = sections[section]
        return currentSection.name


    }

    return nil


}

所以,更清楚地说明我的问题是什么;在我的fetchedresultscontroller中向我的tableView中插入一个新行时,应用程序崩溃并说在解包可选值时它找到了nil。这些部分应按日期排序。

此外,如果不够清楚,这是使用sectionNameKeyPath(formattedDateDue)的代码:

let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: "formattedDateDue", cacheName: "Master")

Breakpoint

以下是请求断点的图片:

1st

还有更多变量,但我无法添加更多图片。

0 个答案:

没有答案
相关问题