Last active
December 4, 2020 23:38
-
-
Save collindonnell/4d082298a86e0f1d1a51 to your computer and use it in GitHub Desktop.
NSManagedObjectContext extension methods to delete all managed objects, or all objects of a given type in the context.
This file contains 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
// | |
// Created by Collin Donnell on 7/22/15. | |
// Copyright (c) 2015 Collin Donnell. All rights reserved. | |
// | |
import CoreData | |
extension NSManagedObjectContext { | |
convenience init(parentContext parent: NSManagedObjectContext, concurrencyType: NSManagedObjectContextConcurrencyType) { | |
self.init(concurrencyType: concurrencyType) | |
parentContext = parent | |
} | |
func deleteAllObjects(error: NSErrorPointer) { | |
if let entitesByName = persistentStoreCoordinator?.managedObjectModel.entitiesByName as? [String: NSEntityDescription] { | |
for (name, entityDescription) in entitesByName { | |
deleteAllObjectsForEntity(entityDescription, error: error) | |
// If there's a problem, bail on the whole operation. | |
if error.memory != nil { | |
return | |
} | |
} | |
} | |
} | |
func deleteAllObjectsForEntity(entity: NSEntityDescription, error: NSErrorPointer) { | |
let fetchRequest = NSFetchRequest() | |
fetchRequest.entity = entity | |
fetchRequest.fetchBatchSize = 50 | |
let fetchResults = executeFetchRequest(fetchRequest, error: error) | |
if error.memory != nil { | |
return | |
} | |
if let managedObjects = fetchResults as? [NSManagedObject] { | |
for object in managedObjects { | |
deleteObject(object) | |
} | |
} | |
} | |
} |
an updated version that works as of Swift 5.3, thanks for the scaffolding:
extension NSManagedObjectContext {
func deleteAllObjects() throws {
guard let entitesByName = persistentStoreCoordinator?.managedObjectModel.entitiesByName else { return }
for (_, entityDescription) in entitesByName {
try deleteAllObjects(for: entityDescription)
}
}
func deleteAllObjects(for entity: NSEntityDescription) throws {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
fetchRequest.entity = entity
let fetchResults = try fetch(fetchRequest)
if let managedObjects = fetchResults as? [NSManagedObject] {
for object in managedObjects {
delete(object)
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Didn't work with Swift 2