Update data
To update the data in our database we just need to do the changes in the instance that we fetched, and then save it using moc
. Let's explain this in a quick example where we added an action to each list row, so when a row is tapped the name is uppercased.
List(persons) { person in
Button {
person.name = person.name?.uppercased()
try? moc.save()
} label: {
Text(person.name ?? "No name")
}
}
Delete data
Remove items using the moc
. After removing the item we need to save again.
moc.delete(person)
try? moc.save()
Sort data
We can sort our fetched data adding one or more NSSortDescriptor
specifying the key path of the property.
@FetchRequest(sortDescriptors: [
NSSortDescriptor(keyPath: \Person.name, ascending: true)
]) var persons: FetchedResults
Predicate
So far we just fetched all the existing items in our Data Model, but we can filter the result using a NSPredicate
.
@FetchRequest(
sortDescriptors: [
NSSortDescriptor(keyPath: \Person.name, ascending: true)
],
predicate: NSPredicate(format: "name == %@", "Python")
) var persons: FetchedResults
Be the first to comment