2016-09-22 76 views
1

如何使用NSBatchDeleteRequest和NSPredicate從CoreData中刪除行。NSBatchDeleteRequest與NSPredicate在swift中

我想刪除超過30天的記錄。

我不想獲取內存中的所有數據並比較和刪除,我想使用NSBatchDeleteRequest,就像我們在NSBatchUpdateRequest中做的那樣。

這是迄今爲止我已經寫

let date = NSDate(); let yesterday = date.dateByAddingTimeInterval(-24*60*60); let predicate = NSPredicate(format: "date > %@", yesterday); 
    let fetchRequest = NSFetchRequest(entityName: "Notification"); 
    let batchDelete = NSBatchDeleteRequest(fetchRequest: fetchRequest) 

請給予解答在迅速

回答

1

這是簡單的例子代碼。可以使用NSPredicate來豐富您的請求。

let calendar = NSCalendar.currentCalendar() 

let thirtyDaysAgo = calendar.dateByAddingUnit(.Day, value: -30, toDate: NSDate(), options: []) 

let fetchRequest = NSFetchRequest(entityName: "Notification") 

fetchRequest.predicate = NSPredicate(format: "(date >= %@)", thirtyDaysAgo) 

let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) 

do { 
    try context.executeRequest(deleteRequest) 
    try context.save() 
} catch { 
    print (error) 
} 
+0

如何轉換是thirtyDaysAgo爲ISO-8601 –

+0

嘗試此解決方案http://stackoverflow.com/questions/16254575/how-do-i-get-iso-8601-date-in-ios –

+0

非常感謝,這對我有幫助。 –