2016-07-28 120 views
1

我試圖從本地通知被觸發時從代碼數據模型中刪除數據。所以,我得到通知的alertbody,然後利用獲取通知的標題數據進行排序:使用UILocalNotification從核心數據中刪除數據

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

@santa你會檢查嗎? –

回答

1

results數組中刪除元素(使用removeAtIndex)不會將其從持久性存儲中刪除 - 或者甚至從上下文中刪除它。你需要告訴上下文以刪除對象:

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

謝謝! –