Created
April 25, 2016 08:46
-
-
Save odrobnik/e289df6e6d79dc38d744e488f8df2da1 to your computer and use it in GitHub Desktop.
Backwards-compatible batch deletion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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