4

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

Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57

1 Answers1

13

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)
  try context.save()
} catch {
  print (error)
}
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100