gpt4 book ai didi

IOS - 如何使用 NSBatchDeleteRequest 清理数据库

转载 作者:行者123 更新时间:2023-11-28 06:54:01 24 4
gpt4 key购买 nike

使用 swift 2.1 和 CoreData,我想删除数据库中的所有数据。

按照下面的方式,效果很好

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.'

我想知道一定是modelcoordinator 有问题,但我不知道如何获得正确的coordinator例如,有人可以帮助我吗?

最佳答案

这一行:

let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)

创建一个新的 persistentStoreCoordinator,与您的模型关联,但不将其链接到 persistentStore。因此出现错误消息。

我怀疑实际上需要使用与您的上下文关联的现有 persistentStoreCoordinator:

let coordinator = context.persistentStoreCoordinator

关于IOS - 如何使用 NSBatchDeleteRequest 清理数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com