0

I want to use core data to store my data. Also, I want to delete the data (row) when I want. I have referenced the site below. https://blckbirds.com/post/core-data-and-swiftui/

The data can be added well, but I want to delete the data without using the List and ForEach{}.onDelete().

However, as a result of my search, I couldn't find a way to delete a row of core data other than using ForEach's .onDelete().

Is there a way to delete specific data (Row) without using list, ForEach onDelete??

JH.KIM
  • 37
  • 4
  • 1
    Does this answer your question https://stackoverflow.com/a/62154314/12299030? – Asperi Jan 23 '21 at 15:36
  • You can have a button which then runs the code: `moc.delete(LIST_ITEM)` then `try? moc.save()`, where `moc` is defined as `@Environment(\.managedObjectContext) private var moc`. (That tutorial uses the variable name `viewContext` instead of `moc`). [This](https://www.hackingwithswift.com/quick-start/swiftui/how-to-delete-core-data-objects-from-swiftui-views) might also be useful. They use `onDelete`, but you don't need to use that. – George Jan 23 '21 at 16:07
  • Does this answer your question? [Delete data from CoreData](https://stackoverflow.com/questions/68375431/delete-data-from-coredata) – lorem ipsum Aug 15 '21 at 19:39

1 Answers1

1
import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var context
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Order.timestamp, ascending: true)],
        animation: .default)
    private var orders: FetchedResults<Order>

//.....your code....

for order in orders {
  if order.name == «KuKu” {//here is your condition 
  self.deleteSelectedOrder(selectedOrder: order)
  }
}
func deleteSelectedOrder(selectedOrder: Order){
  context.delete(selectedOrder as! NSManagedObject)
            do {
                try context.save()
            } catch {
               
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
}
Evgeny Lisin
  • 441
  • 1
  • 4
  • 7