1
使用swift 2.1和CoreData,我想刪除我的數據庫的所有數據。IOS - 如何用NSBatchDeleteRequest清理數據庫
用下面的方式,它的工作原理以及
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()
}
,但我聽說有一個更好的方式來做到這一點與 NSBatchDeleteRequest
這裏是代碼
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)
但它提出了一個錯誤說
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.'
我想一定有什麼不對的模式或協調,但我無法弄清楚如何得到正確的協調例如,有人能幫助我嗎?