Filtering data with predicates

A common operation you'll want to perform on your database is filtering. In Core Data, you make use of predicates to do this. A predicate describes a set of rules that any object that gets fetched has to match.

If you're modeling your data, it's wise to think about the types of filtering you will need to do. For instance, you may be building a birthday calendar where you'll often sort or filter on dates. If this is the case, you should make sure that you have Core Data index this property. You can enable this with a checkbox in the model editor.

Writing predicates can be confusing, especially if you try to think of them as the where clause from SQL. Predicates are very similar, but they're not quite the same. A simple predicate will look as follows:

NSPredicate(format: "name CONTAINS[n] %@", "Gu") 

A predicate has a format; this format always starts with a key. This key represents the property you want to match on. In this example, it would be the name of a family member. Then, you will specify the condition, for instance ==, >, < or CONTAINS[n]. There are more conditions available, but these are some examples of conditions you'll commonly use. Finally, you will specify a placeholder that we'll substitute. This placeholder is %@.

The example predicate is very simple and bare; it could be the template for a search feature you're building. Usually, a simple search doesn't have to be much more complex than this as long as there's an index added to the properties you'll search for.

If you have multiple predicates you want to match on, you can combine them using an NSCompoundPredicate. This class will combine different predicates using either an and, or, or not clause. A common use case for this approach is when you build a complex filter in your app.

To make use of a predicate, you assign it to the predicate property of a fetch request. Every fetch request has a predicate property that you can set. It can handle both a single predicate and a compound predicate. If you set this property before executing the fetch request, the predicate will be applied and your dataset will be filtered.

Predicates are really powerful, and they have many options available. If you're interested in an in-depth overview of predicates and all of the ways in which you can make use of format strings, I recommend that you read Apple's Predicate Programming Guide. It provides a really well-documented overview of predicates and their uses.

Next up, we'll cover how to handle the changing data in your application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.230.81