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 objects that match a filter are retrieved from the repository and transformed into actual objects.
A predicate is a condition 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, such as in 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, meaning that it must be created at the beginning. It cannot change during the life cycle of the view as a result of a search text field, for example.
In this recipe, we'll learn how to create a dynamic filter for a contact list, where the user...