Reputation: 47
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??
Upvotes: 0
Views: 355
Reputation: 461
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)")
}
}
Upvotes: 1