如何在Swift中删除实体核心数据中的所有条目?
我想要一个deleteAll()方法,这样我就可以清除数据库了。
这就是我目前所拥有的:

func deleteAllCoreData() {
    let fetchRequest = NSFetchRequest(entityName: "DataPoint")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

    do {
        try coordinator.executeRequest(deleteRequest, withContext: managedContext)
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }

}

但它有一个错误:
未知的命令类型(实体:数据点;谓词:
((空));sortDescriptors:((空));类型:
nsmanagedObjectDresultType;)>

最佳答案

iOS 9添加了一个名为NSBatchDeleteRequest的新类,该类允许您轻松删除与谓词匹配的对象,而无需将它们全部加载到内存中。以下是您的使用方法:

let fetchRequest = NSFetchRequest(entityName: "Foo")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

do {
    //`myPersistentStoreCoordinator` is from the core data stack
    try myPersistentStoreCoordinator.executeRequest(deleteRequest, withContext: myContext)
} catch let error as NSError {
    // TODO: handle the error
}

关于swift - 在Swift 2中删除实体的核心数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36829307/

10-12 13:37