Filtering Core Data requests using a Predicate
An essential characteristic of Core Data is the possibility of filtering the results of a @FetchRequest
so that only the data that matches a filter is retrieved from the repository and transformed into actual Swift objects.
A predicate is a condition that the Core Data objects must satisfy to be fetched; for example, the name must be shorter than 5 characters, or the age of a person should be greater than 18. The conditions in a predicate can also be composite; for example, fetch all the data where the name is equal to “Lewis” and the age is greater than 18.
Even though the property wrapper accepts NSPredicate
, which is a filter for Core Data, the problem is that this cannot be dynamic, which means that it must be created at the beginning. It cannot change during the life cycle of the view because of a search text field.
In this recipe, we’ll learn how to create a dynamic filter for a contact list, where...