2015-12-09 46 views
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.' 

我想一定有什麼不對的模式協調,但我無法弄清楚如何得到正確的協調例如,有人能幫助我嗎?

回答

1

這條線:

let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) 

創建一個新的persistentStoreCoordinator,與你的模型有關,但它並沒有鏈接到一個persistentStore。因此錯誤信息。

我居然懷疑需要使用與上下文相關聯的現有persistentStoreCoordinator

let coordinator = context.persistentStoreCoordinator