iOS: Delete ALL Core Data Swift

前端 未结 23 677
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 11:20

I am a little confused as to how to delete all core data in swift. I have created a button with an IBAction linked. On the click of the button I have the follow

相关标签:
23条回答
  • 2020-12-04 12:00

    In Swift UI

    when you select core data at the beginning of project the persistence coordinator is automatically created by swift in app delegate. The scene delegate creates @environmentObject for managed context

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    let contentView = ContentView().environment(\.managedObjectContext, context)
    

    create instance of manageObjectContext in content view and also fetchRequest object using property wrapper @FetchRequest

    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: EntityName.entity(), sortDescriptors: []) var entityNames: FetchedResults<EntityName>
    

    For delete action perform

    for entityName in entityNames {
    moc.delete(entityName)
    }
    try? moc.save()
    

    try operation can throw error so please implement do try catch block in production code to handle error properly.

    0 讨论(0)
  • 2020-12-04 12:00

    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)")
        }
    }
    
    0 讨论(0)
  • 2020-12-04 12:01

    For 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)
        }
    
    
      }
    
    0 讨论(0)
  • 2020-12-04 12:01
    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)
        }
    
    }
    
    0 讨论(0)
  • 2020-12-04 12:03

    Try this:

    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) }
    }
    
    0 讨论(0)
提交回复
热议问题