我对如何删除swift中的所有核心数据感到困惑。我创建了一个链接IBAction
的按钮。点击按钮后,我有以下内容:
let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
然后我用各种方法搞砸了尝试删除所有核心数据内容,但我似乎无法让它发挥作用。我已经使用removeAll从存储的数组中删除但仍无法从核心数据中删除。我假设我需要某种类型的for循环但不确定如何从请求中创建它。
我尝试应用删除单行的基本原则
func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
if editingStyle == UITableViewCellEditingStyle.Delete {
if let tv = tblTasks {
context.deleteObject(myList[indexPath!.row] as NSManagedObject)
myList.removeAtIndex(indexPath!.row)
tv.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
}
var error: NSError? = nil
if !context.save(&error) {
abort()
}
}
}
然而,问题在于,当我点击一个按钮时,我没有indexPath值,而且我需要遍历所有我无法用上下文做的值。
答案 0 :(得分:48)
尝试这个简单的解决方案:
func deleteAllData(entity: String)
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.executeFetchRequest(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.deleteObject(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
}
}
Swift 4
func deleteAllData(_ entity:String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try dataController.viewContext.fetch(fetchRequest)
for object in results {
guard let objectData = object as? NSManagedObject else {continue}
dataController.viewContext.delete(objectData)
}
} catch let error {
print("Detele all data in \(entity) error :", error)
}
}
<强>实施强>
self.deleteAllData("your_entityName")
答案 1 :(得分:22)
要删除所有数据,您可以使用NSBatchDeleteRequest
func deleteAllData(entity: String)
{
let ReqVar = NSFetchRequest(entityName: entity)
let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: ReqVar)
do { try ContxtVar.executeRequest(DelAllReqVar) }
catch { print(error) }
}
答案 2 :(得分:18)
我使用以下方法使用它:
@IBAction func btnDelTask_Click(sender: UIButton){
let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Food")
myList = context.executeFetchRequest(request, error: nil)
if let tv = tblTasks {
var bas: NSManagedObject!
for bas: AnyObject in myList
{
context.deleteObject(bas as NSManagedObject)
}
myList.removeAll(keepCapacity: false)
tv.reloadData()
context.save(nil)
}
}
但是,我不确定这是否是最好的方法。我也收到一个'常数'bas'被推断为有任何对象'错误 - 所以如果有任何解决方案,那么它会很棒
修改强>
通过更改为bas:AnyObject
进行修复答案 3 :(得分:11)
Swift 3.0
func DeleteAllData(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: "Entity"))
do {
try managedContext.execute(DelAllReqVar)
}
catch {
print(error)
}
}
答案 4 :(得分:3)
在Swift 3.0中
func deleteAllRecords() {
//delete all data
let context = appDelegate.persistentContainer.viewContext
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "YourClassName")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try context.execute(deleteRequest)
try context.save()
} catch {
print ("There was an error")
}
}
答案 5 :(得分:3)
Swift 5.1
此处的大部分帖子建议创建一个函数,以按 name 删除所有实体,然后按名称删除所有实体。像这样:
resetEntity(named: "MyEntity1")
resetEntity(named: "MyEntity2")
resetEntity(named: "MyEntity3")
...
但是,如果真正的问题是如何一次性清理所有CoreData实体,建议您遍历实体名称:
// Supposing this is a CoreDataController/CoreDataStack class where you have access to `viewContext` and `persistantContainer`
// Otherwise just pass the `persistantContainer` as a parameter, from which you can also retrieve the `viewContext`
func resetAllCoreData() {
// get all entities and loop over them
let entityNames = self.persistentContainer.managedObjectModel.entities.map({ $0.name!})
entityNames.forEach { [weak self] entityName in
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try self?.context.execute(deleteRequest)
try self?.context.save()
} catch {
// error
}
}
}
希望这会有所帮助
答案 6 :(得分:3)
在Swift用户界面
当您在项目开始时选择核心数据时,持久性协调器是由应用程序委托中的swift自动创建的。场景委托为托管上下文创建@environmentObject
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let contentView = ContentView().environment(\.managedObjectContext, context)
在内容视图中创建manageObjectContext实例,并使用属性包装器@FetchRequest创建fetchRequest对象
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: EntityName.entity(), sortDescriptors: []) var entityNames: FetchedResults<EntityName>
要执行删除操作
for entityName in entityNames {
moc.delete(entityName)
}
try? moc.save()
try操作可能会引发错误,因此请在生产代码中实施try try catch块以正确处理错误。
答案 7 :(得分:3)
适用于Swift 4.0 (svmrajesh's answer的修改版本...或至少Xcode将其转换为适用于我之前的版本。)
func deleteAllData(entity: String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.delete(managedObjectData)
}
} catch let error as NSError {
print("Delete all data in \(entity) error : \(error) \(error.userInfo)")
}
}
<强>实施强>
deleteAllData(entity: "entityName")
答案 8 :(得分:3)
这个clean()方法将从DataModel获取实体列表并清除所有数据。
func deleteAll(entityName: String) -> Error? {
if #available(iOS 9.0, *) {
do {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
try context.execute(batchDeleteRequest)
} catch {
return error
}
return nil
} else {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try context.fetch(fetchRequest)
for managedObject in results
{
if let managedObjectData:NSManagedObject = managedObject as? NSManagedObject {
context.delete(managedObjectData)
}
}
} catch {
return error
}
return nil
}
}
var objectModel: NSManagedObjectModel? {
if #available(iOS 10.0, *) {
return persistentContainer.managedObjectModel
} else {
return persistentStoreCoordinator?.managedObjectModel
}
}
open func clean() {
if let models = objectModel?.entities {
for entity in models {
if let entityName = entity.name {
_ = deleteAll(entityName: entityName)
}
}
}
}
快乐的编码!
答案 9 :(得分:2)
这是我基于Jayant Dash优秀(全面)答案清除Swift 3中所有核心数据的实现。由于仅支持iOS10 +,因此更简单。它删除所有核心数据实体,而无需对其进行硬编码。
public func clearAllCoreData() {
let entities = self.persistentContainer.managedObjectModel.entities
entities.flatMap({ $0.name }).forEach(clearDeepObjectEntity)
}
private func clearDeepObjectEntity(_ entity: String) {
let context = self.persistentContainer.viewContext
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try context.execute(deleteRequest)
try context.save()
} catch {
print ("There was an error")
}
}
答案 10 :(得分:1)
另一种方法是完全删除并重新创建持久存储(iOS 10 +,swift 3)。
let urls = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask);
var dbUrl = urls[urls.count-1];
dbUrl = dbUrl.appendingPathComponent("Application Support/nameOfYourCoredataFile.sqlite")
do {
try persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: dbUrl, ofType: NSSQLiteStoreType, options: nil);
} catch {
print(error);
}
do {
try persistentContainer.persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbUrl, options: nil);
} catch {
print(error);
}
答案 11 :(得分:1)
据我所知,有两种简单的方法,首先是
方法1:
//初始化获取请求
<md-item-template>
<span md-highlight-text="ctrl.searchText"
md-highlight-flags="i">{{item.display}}</span>
</md-item-template>
//配置获取请求
let fetchRequest = NSFetchRequest(entityName: "Item")
}
Methode 2:
//创建获取请求
fetchRequest.includesPropertyValues = false
do {
let items = try managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
for item in items {
managedObjectContext.deleteObject(item)
}
// Save Changes
try managedObjectContext.save()
} catch {
// Error Handling
// ...
//创建批量删除请求
let fetchRequest = NSFetchRequest(entityName: "Item")
我测试了两者并且它们都工作正常
答案 12 :(得分:1)
您可以尝试使用iOS 9.0+和swift 3 +这样的内容:
public func clearDatabase()
{
let url = persistentContainer.persistentStoreDescriptions.first?.url
guard url != nil else {
return
}
let persistentStoreCoordinator = persistentContainer.persistentStoreCoordinator
do {
try persistentStoreCoordinator.destroyPersistentStore(at:url!, ofType: NSSQLiteStoreType, options: nil)
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url!, options: nil)
} catch let error {
print(name.uppercased() + ": Clear store: " + error.localizedDescription)
}
}
答案 13 :(得分:1)
快捷键5
func deleteAllData(entity: String){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do {
let arrUsrObj = try managedContext.fetch(fetchRequest)
for usrObj in arrUsrObj as! [NSManagedObject] {
managedContext.delete(usrObj)
}
try managedContext.save() //don't forget
} catch let error as NSError {
print("delete fail--",error)
}
}
答案 14 :(得分:0)
试试这个:
func deleteAllData(entity: String)
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let ReqVar = NSFetchRequest(entityName: entity)
let DelAllReqVar = NSBatchDeleteRequest(fetchRequest: ReqVar)
do { try ContxtVar.executeRequest(DelAllReqVar) }
catch { print(error) }
}
答案 15 :(得分:0)
Swift 3
// Replace 'MyEntityName' with your managed object class.
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest: NSFetchRequest<MyEntityName> = MyEntityName.fetchRequest()
fetchRequest.returnsObjectsAsFaults = false
moc.perform {
do {
let myEntities = try fetchRequest.execute()
for myEntity in myEntities {
moc.delete(myEntity)
}
try moc.save()
} catch let error {
print("Delete Error: \(error.localizedDescription)")
}
}
答案 16 :(得分:0)
快捷键4:
destroyPersistentStoreAtURL(_:withType:options:)将删除(或截断)目标持久性存储。这将安全地破坏持久性存储。
添加:
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreURL, options: nil)
} catch {
// Error Handling
}
销毁/删除/截断:
do {
try persistentStoreCoordinator.destroyPersistentStoreAtURL(persistentStoreURL, withType: NSSQLiteStoreType, options: nil)
} catch {
// Error Handling
}
注意:上面方法中的参数应该与addPersistentStoreWithType方法相同。 您需要重新启动storeCoordinator才能再次使用商店。
答案 17 :(得分:0)
对于Swift 4.0
func deleteAllData(_ entity:String) {
let managedContext = DatabaseController.getContext().persistentStoreCoordinator
let context = DatabaseController.getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try managedContext?.execute(batchDeleteRequest, with: context)
}
catch {
print(error)
}
}
答案 18 :(得分:0)
从iOS 9开始,可能会删除永久性存储。 为了更好地维护,请使用抽象函数创建 NSPersistentStoreCoordinator 扩展。
extension NSPersistentStoreCoordinator {
func destroyPersistentStore(type: String) -> NSPersistentStore? {
guard
let store = persistentStores.first(where: { $0.type == type }),
let storeURL = store.url
else {
return nil
}
try? destroyPersistentStore(at: storeURL, ofType: store.type, options: nil)
return store
}
}
然后销毁SQLite持久存储看起来很简单:
let coordinator = persistentContainer.persistentStoreCoordinator
let store = coordinator.destroyPersistentStore(type: NSSQLiteStoreType)
答案 19 :(得分:0)
Swift 5.1
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try coreDataManager.managedObjectContext.execute(batchDeleteRequest)
} catch {
print("Detele all data in \(entityName) error :", error)
}
答案 20 :(得分:0)
static func fetch<T>(entity: T.Type, withPredicate predicate: NSPredicate? = nil) -> Array<T>? where T : NSManagedObject {
let request: NSFetchRequest<T> = NSFetchRequest<T>(entityName: String(describing: T.self))
request.predicate = predicate
do {
return try context.fetch(request)
}catch{
print(error.localizedDescription)
}
return nil
}
static func delete<T>(_ object: T) where T : NSManagedObject {
context.delete(object)
saveContext()
}
static func reset<T>(entity: T.Type) where T : NSManagedObject {
fetch(entity: entity.self)?.forEach{
delete($0)
}
}
答案 21 :(得分:0)
我用这个来删除Swift3中的所有核心数据实体
func deleteAllCD(){
for entityName in ["EntityName", "AnotherEntityName"]{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let delAllReqVar = NSBatchDeleteRequest(fetchRequest: request)
do { try persistentContainer.viewContext.execute(delAllReqVar) }
catch { print(error) }
}
}
答案 22 :(得分:0)
与上面类似,但是取出了AppDelegte调用并使用了UIView变量
var context: NSManagedObjectContext?
//deleting Message
func deleteMessages(entity: String) {
do {
let request = NSFetchRequest(entityName: entity)
print(request)
if let result = try context!.executeFetchRequest(request) as? [your class of NSManagedObject] {
for message in result {
context!.deleteObject(message)
try context!.save()
print(message)
self.tableView.reloadData()
}
}
} catch {
print("miss")
}
}
使用通话功能
self.deleteMessages("TimeMaster")
答案 23 :(得分:0)
要删除 Core Data 中的所有条目,我找到了两种方法
1 - 带有 for
函数
func deleteEntries() {
do {
let managedObjectContext = try CoreDataStack.sharedInstance.getContext()
for record in records {
managedObjectContext.delete(record)
}
try managedObjectContext.save()
} catch let error {
print(error.localizedDescription)
}
}
2 - 带有 NSBatchDeleteRequest
func deleteEntries() {
do {
let managedObjectContext = try CoreDataStack.sharedInstance.getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Location")
let request: NSBatchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
try managedObjectContext.execute(request)
try managedObjectContext.save()
} catch let error {
print(error.localizedDescription)
}
}
我建议使用数字 2,因为这是处理应用中资源的更好方法