Reputation: 854
With swift 2.1 and CoreData, I want to delete all data of my database.
with following way, it works well
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let request = NSFetchRequest(entityName: "UserCourse")
let arr = try! context.executeFetchRequest(request)
for item in arr{
context.deleteObject(item as! NSManagedObject)
try! context.save()
}
but i heard that there is a better way to do that with NSBatchDeleteRequest
here is the code
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let model = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectModel
let delete = NSBatchDeleteRequest(fetchRequest: NSFetchRequest(entityName: "Data"))
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
try! coordinator.executeRequest(delete, withContext: context)
but it raise an error said
2015-12-10 01:36:21.195 test[1090:40088] CoreData: error: Illegal attempt to save to a file that was never opened. "This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation.". No last error recorded.
2015-12-10 01:36:21.202 test[1090:40088] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation.'
I wonder there must be something wrong with the model or coordinator, but I can't figure out how to get a correct coordinator instance, someone can help me?
Upvotes: 1
Views: 707
Reputation: 21536
This line:
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
creates a new persistentStoreCoordinator
, associated with your model, but does not link it to a persistentStore
. Hence the error message.
I suspect actually need to use the existing persistentStoreCoordinator
associated with your context:
let coordinator = context.persistentStoreCoordinator
Upvotes: 1