O'Reilly logo

Core Data in Swift by Marcus S. Zarra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Bulk Deletes

The API for handling bulk deletes was added to Core Data after bulk updates. Therefore the API is very similar.

 func​ deleteOldRecipes() {
 guard​ ​let​ moc = writerContext ​else​ {
  fatalError(​"Writer context is nil"​)
  }
 
  moc.perform {
 let​ yOld = ​self​.dateFrom1YearAgo()
 let​ fetch = ​NSFetchRequest​<​NSFetchRequestResult​>(entityName: ​"Recipe"​)
  fetch.predicate = ​NSPredicate​(format: ​"lastUsed <= %@"​, yOld ​as​ ​CVarArg​)
 let​ request = ​NSBatchDeleteRequest​(fetchRequest: fetch)
  request.resultType = .resultTypeObjectIDs
 
 do​ {
 guard​ ​let​ result = ​try​ moc.execute(request)
 as?​ ​NSBatchDeleteResult​ ​else​ {
  fatalError(​"Unexpected result from ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required