Predicates in Core Data

Database programming is all about filtering and sorting tables linked to each other. According to the book Core Data, «Core Data is Apple’s object graph management and persistency framework for iOS, OS X, watchOS, and tvOS.»

In a sense, predicates are an object version of the WHERE clause in SQL. Just like NSFetchRequest represent the FROM clause in SQL.

I never have had problems with WHERE and FROM in SQL, but the predicate format strings in Core Data has been quite a struggle for me.

I don’t think the struggle is only my fault. Predicates should clearly be thought, at least to me, as a method of writing WHERE clauses.

Here is some notes from tutplus’ Core Data and Swift: Relationships and More Fetching:

let predicate = NSPredicate(format: "%K == %@", "last", "Doe")

The predicate format string uses %K (K stands for Key) for the property name and %@ for the value.

let predicate = NSPredicate(format: "%K >= %i", "age", 30)

Here the predicate format string uses %i for the integer value.

The Core Data book’s chapter on Predicates, recommends to use a variable for both the key and the value part of the format string. Then the compiler or debugger will be able to stop us and tell if the format string isn’t valid.

And for the sake of completeness, some notes from Wikipedia.

Core Data filters tables using predicates.

In mathematics, a predicate is commonly understood to be a Boolean-valued function P: X→ {true, false}, called the predicate on X.

In Core Data predicates are attributes to FetchRequest object.