当我从 table 视图和核心数据中删除时,应用程序崩溃

App crashes when I delete from table view and core data

我有一个 table 视图设置为从 coredata 中提取。当我从 table 视图中删除时,应用程序崩溃并显示以下错误消息

fatal error: unexpectedly found nil while unwrapping an Optional value

我已经找出发生这种情况的代码行。该行代码中的两个字符串均为 nil。因此,出于某种原因,当我在删除后从 fetchResultsController 中拉出它时,它拉出一个空的 customer.It 确实删除了客户但崩溃了。当我启动应用程序备份时,客户已经消失了。

cell.textLabel!.text = (cust.valueForKey("firstName")! as! String) + " " + (cust.valueForKey("lastName")! as! String)

下面是应该相关的其余函数。如果您需要更多代码,请告诉我。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell
{
    let cust = self.fetchResultsController.objectAtIndexPath(indexPath!)
    print("Cust: \(cust)")
    let cell =
    tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath!)
    print(cust.valueForKey("firstName"))
    print(cust.valueForKey("lastName"))
    cell.textLabel!.text = (cust.valueForKey("firstName")! as! String) + " " + (cust.valueForKey("lastName")! as! String)
    return cell
}

lazy var fetchResultsController:NSFetchedResultsController =
{
    var fetchRequest = NSFetchRequest(entityName:"Customer")
    print("fetchRequest\(fetchRequest)")
    let primarySortDescriptor = NSSortDescriptor(key: "lastName", ascending: true)
    let secondarySortDescriptor = NSSortDescriptor(key: "firstName", ascending: true)
    fetchRequest.sortDescriptors = [primarySortDescriptor,secondarySortDescriptor]
    let frc = NSFetchedResultsController(
        fetchRequest: fetchRequest,
        managedObjectContext: self.context,
        sectionNameKeyPath: nil,
        cacheName: nil)
    print(self.context)
    let fdrc = NSFetchedResultsController(
        fetchRequest: fetchRequest,
        managedObjectContext: self.context,
        sectionNameKeyPath: "first",
        cacheName: nil)
    self.fetchedResultsController = fdrc
    print("fetchedResultsController:\(self.fetchedResultsController)")
    return self.fetchedResultsController

}()
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
   let object:NSManagedObject = self.fetchedResultsController.objectAtIndexPath(indexPath)
   context.deleteObject(object)
   try! context.save()
   tableView.reloadData()
   //self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 
}


func controllerDidChangeContent(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)
{
    tableView.deleteRowsAtIndexPaths(NSArray(object:indexPath!) as! [NSIndexPath], withRowAnimation: UITableViewRowAnimation.Fade)
    tableView.reloadData()
}

问题是我没有实现所有的 fetchedResultsControllerDelegate 方法。一旦我添加了所有四种方法,删除就完美无缺了。谢谢大家的帮助。