如何使用带有NSPredicate的NSBatchDeleteRequest从CoreData中删除行。
我想删除超过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)
请快速给出答案
答案 0 :(得分:5)
这是一个简单的例子。使用过滤您的请求的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)
}