我试图在触发本地通知时从代码数据模型中删除数据。因此,我收到通知alertbody
,然后使用通知标题获取排序数据:
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()
}
当我从模型中删除数据并转到事件视图控制器时,我仍然可以看到数据存在!我错过了什么吗?!感谢。
答案 0 :(得分:1)
从results
数组中删除元素(使用removeAtIndex
)不会将其从持久存储中删除 - 甚至不会从上下文中删除。您需要告诉上下文删除对象:
let object = results[0] as! NSManagedObject
context.deleteObject(object)