简体   繁体   中英

Delete Object from CoreData (error)

I'd like to delete an object from core data. I tried this code but it's not working. What's wrong? I'm working with Swift and Xcode 6.1.1.

Code:

    let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
    var daten = [TaskModel]() //CoreData Entity

    managedObjectContext!.deleteObject(daten[indexPath.row])
    appDelegate.saveContext()
    let fetchRequest = NSFetchRequest(entityName: "TaskModel")
    daten = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as [TaskModel]
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Right)

daten is an empty array.

Therefore, daten[x] will crash.

In your case, x is indexPath.row , but it will crash with any value.
If you try to access an element of an empty array by index, you will get the above error.

To get an object from your fetched results controller and delete it,

let task = self.fetchedResultsController.objectAtIndexPath(indexPath) as TaskModel
self.fetchedResultsController.managedObjectContext.deleteObject(task)
self.fetchedResultsController.managedObjectContext.save(nil)

The standard implementation of the fetched results controller from the Xcode template will take care of updating your table view automatically, you even get animation for free.

If you are not using a NSFetchedResultsController , stop here and refactor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM