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

时间:2015-06-18 05:58:27

标签: swift tableview ios9

我有一个表格视图,可以从coredata中提取。当我从表格视图中删除时,它会使应用程序崩溃,并显示以下错误消息

fatal error: unexpectedly found nil while unwrapping an Optional value

我已经找到了发生这种情况的代码行。该行代码中的两个字符串都是nil。因此,出于某种原因,当我在删除后从fetchResultsController中提取它时会拉出一个空客户。它会删除客户但崩溃了。当我启动应用程序备份时,客户就会失败了。

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()
}

1 个答案:

答案 0 :(得分:0)

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