Vlad Mihai Vlad Mihai - 7 months ago 15
Swift Question

Delete from Core Data

I work on an iOS App application that stores some data in Core Data. I found a problem when I had to delete specific data from Core Data.

Although it says that the delete was successfull, the number of elements stored are the same.

Can you take a look ?

Here's the code :

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Session")
fetchRequest.returnsObjectsAsFaults = false

do
{
var session = try managedContext.executeFetchRequest(fetchRequest) as! [Session]

managedContext.deleteObject(session.first!)
if session.first!.deleted {
print("Succesfully deleted")
print(session.count)
}
else {
print("Unsuccesfull")
}


} catch {
print("Detele error : \(error)")
}

Answer

As @Vadian said, you forgot to save the context.

So let implement it:

do {
   try managedContext.save()  
} catch let error as NSError {
   print(error)
}
Comments