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??

3
  • 1
    Does this answer your question stackoverflow.com/a/62154314/12299030? Commented Jan 23, 2021 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 might also be useful. They use onDelete, but you don't need to use that. Commented Jan 23, 2021 at 16:07
  • Does this answer your question? Delete data from CoreData Commented Aug 15, 2021 at 19:39

1 Answer 1

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)")
            }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.