// Capítulo 5: Actualización y eliminación de datos en CoreData
// Para actualizar y eliminar objetos en CoreData utilizando SwiftUI, podemos utilizar el contexto de CoreData. A continuación se muestra:
Button("Update") {
let request: NSFetchRequest<Product> = Product.fetchRequest()
request.predicate = NSPredicate(format: "name == %@", "iPhone")
do {
let products = try context.fetch(request)
if let product = products.first {
product.price = 899.99
try context.save()
}
} catch {
print(error.localizedDescription)
}
}
Button("Delete") {
let request: NSFetchRequest<Product> = Product.fetchRequest()
request.predicate = NSPredicate(format: "name == %@", "iPhone")
do {
let products = try context.fetch(request)
if let product = products.first {
context.delete(product)
try context.save()
}
} catch {
print(error.localizedDescription)
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter