Mc.Lover Mc.Lover - 4 months ago 32
Swift Question

Remove data from core data using UILocalNotification

I am trying to remove a data from code data model when local notification is fired. So I get notifications's

alertbody
,then fetch sort data using notification title :

func application(application: UIApplication, handleActionWithIdentifier identifier: String?,
forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {


if identifier == "deleteEvent" {

context = CoreDataStack.managedObjectContext

do {

request = NSFetchRequest(entityName: "Event")
let titlePredicate = NSPredicate(format: "title CONTAINS[c] %@" ,notification.alertBody!)

request.predicate = titlePredicate
results = try context.executeFetchRequest(request)

print(results.count) // returns 1



} catch {

print("ERROR")
}

do {

results.removeAtIndex(0)
CoreDataStack.saveContext()

NSNotificationCenter.defaultCenter().postNotificationName("reloadTableView", object: nil)
print(results.count) // returns 0

}


}

completionHandler()
}


when I remove the data from the model and go to event view controller for example still I can see the data is there ! Am I missing something ?! thanks.

Answer

Removing an element from the results array (using removeAtIndex) does not delete it from the persistent store - or even from the context. You need to tell the context to delete the object:

let object = results[0] as! NSManagedObject
context.deleteObject(object)
Comments