Anirudha Mahale Anirudha Mahale - 1 month ago 3x
Swift Question

NSBatchDeleteRequest with NSPredicate in swift

How to delete rows from CoreData using NSBatchDeleteRequest with NSPredicate.

I want to delete the records which are older than 30 days.

I dont want to get all the data in the memory and than compare and delete, I want to use NSBatchDeleteRequest, like we do in NSBatchUpdateRequest.

Here is the code so far I have written

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)

Please give answers in swift


This is simple example. It is possible to rich with using of the NSPredicate that will filter your request.

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)
} catch {
  print (error)