Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 271
Anirudha Mahale Avatar asked Oct 21 '25 13:10

Anirudha Mahale


1 Answers

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)
}
like image 128
Oleg Gordiichuk Avatar answered Oct 23 '25 04:10

Oleg Gordiichuk