Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Created April 25, 2016 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odrobnik/e289df6e6d79dc38d744e488f8df2da1 to your computer and use it in GitHub Desktop.
Save odrobnik/e289df6e6d79dc38d744e488f8df2da1 to your computer and use it in GitHub Desktop.
Backwards-compatible batch deletion
extension NSPersistentStoreCoordinator
{
func batchDelete(fetchRequest: NSFetchRequest) throws
{
// create a worker
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.persistentStoreCoordinator = self
var retError: NSError!
context.performBlockAndWait
{
do
{
if #available(iOS 9.0, *)
{
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
try self.executeRequest(deleteRequest, withContext: context)
}
else // Fallback on earlier versions
{
// make copy of request with some modifications
let deleteRequest = NSFetchRequest(entityName: fetchRequest.entityName!)
deleteRequest.predicate = fetchRequest.predicate
deleteRequest.includesPropertyValues = false
// fetch all
let result = try context.executeFetchRequest(deleteRequest) as! [NSManagedObject]
// delete
for object in result
{
context.deleteObject(object)
}
// save context
try context.save()
}
}
catch let error as NSError
{
retError = error
}
}
if retError != nil
{
throw retError
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment