iOS: Delete ALL Core Data Swift

前端 未结 23 684
爱一瞬间的悲伤
爱一瞬间的悲伤 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
    

    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.

提交回复
热议问题