Core Data II
Update, delete, sort and predicate.
Core Data II
Update, delete, sort and predicate.
0
0
Checkbox to mark video as read
Mark as read

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

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy