Nspredicate Cheat Sheet



This document describes in general how you use predicates, and how the use of predicates may influence the structure of your application data.

  1. Nspredicate Cheat Sheet Pdf
  2. Nspredicate Cheat Sheet
  3. Nspredicate Cheat Sheet Template
  • UI Testing Cheat Sheet alternatives and similar libraries Based on the 'UI Testing' category. Alternatively, view UI Testing Cheat Sheet alternatives based on common mentions on social networks and blogs.
  • Enjoy this cheat sheet at its fullest within Dash, the macOS documentation browser. Basic Functionality Testing if an element exists. Let firstPredicate = NSPredicate (format: 'label BEGINSWITH 'First Picker') let firstPicker = app.

Evaluating Predicates

To evaluate a predicate, you use the NSPredicate method evaluateWithObject: and pass in the object against which the predicate will be evaluated. The method returns a Boolean value—in the following example, the result is YES.

You can use predicates with any class of object, but the class must support key-value coding for the keys you want to use in a predicate.

NSPredicate examples available here or is a good NSPredicate cheat sheet. NSPredicate covers element id search with 'name accessibilityIdentifier' predicate.

Using Predicates with Arrays

NSArray and NSMutableArray provide methods to filter array contents. NSArray provides filteredArrayUsingPredicate: which returns a new array containing objects in the receiver that match the specified predicate. NSMutableArray provides filterUsingPredicate: which evaluates the receiver’s content against the specified predicate and leaves only objects that match.

If you use the Core Data framework, the array methods provide an efficient means of filtering an existing array of objects without—as a fetch does—requiring a round trip to a persistent data store.

Using Predicates with Key-Paths

Recall that you can follow relationships in a predicate using a key path. The following example illustrates the creation of a predicate to find employees that belong to a department with a given name (but see also Performance).

If you use a to-many relationship, the construction of a predicate is slightly different. If you want to fetch Departments in which at least one of the employees has the first name 'Matthew,' for instance, you use an ANY operator as shown in the following example:

If you want to find Departments in which at least one of the employees is paid more than a certain amount, you use an ANY operator as shown in the following example:

Using Null Values

A comparison predicate does not match any value with null except null (nil) or the NSNull null value (that is, ($value nil) returns YES if $value is nil). Consider the following example.

The predicate does match the dictionary that contains a value Ben for the key firstName, but does not match the dictionary with no value for the key firstName. The following code fragment illustrates the same point using a date and a greater-than comparator.

Testing for Null

If you want to match null values, you must include a specific test in addition to other comparisons, as illustrated in the following fragment.

By implication, a test for null that matches a null value returns true. In the following code fragment, ok is set to YES for both predicate evaluations.

Using Predicates with Core Data

If you are using the Core Data framework, you can use predicates in the same way as you would if you were not using Core Data (for example, to filter arrays or with an array controller). In addition, however, you can also use predicates as constraints on a fetch request and you can store fetch request templates in the managed object model (see Managed Object Models).

Limitations: You cannot necessarily translate “arbitrary” SQL queries into predicates or fetch requests. There is no way, for example, to convert a SQL statement such as

into a fetch request. You must fetch the objects of interest, then either perform a calculation directly using the results, or use an array operator.

Fetch Requests

You create a predicate to match properties of the target entity (note that you can follow relationships using key paths) and associate the predicate with a fetch request. When the request is executed, an array is returned that contains the objects (if any) that match the criteria specified by the predicate. The following example illustrates the use of a predicate to find employees that earn more than a specified amount.

Object Controllers

If you are using Cocoa bindings, you can specify a fetch predicate for an object controller (such as an instance of NSObjectController or NSArrayController). You can type a predicate directly into the predicate editor text field in the Attributes Inspector in Xcode or you can set it programmatically using setFetchPredicate:. The predicate is used to constrain the results returned when the controller executes a fetch. If you are using an NSObjectController object, you specify a fetch that uniquely identifies the object you want to be the controller's content—for example, if the controller’s entity is Department, the predicate might be name like 'Engineering'.

Using Regular Expressions

The MATCHES operator uses ICU's Regular Expressions package, as illustrated in the following example:

According to the ICU specification, regular expression metacharacters are not valid inside a pattern set. For example, the regular expression d{9}[dxX] does not match valid ISBN numbers (any ten digit number, or a string with nine digits and the letter 'X') since the pattern set ([dxX]) contains a metacharacter (d). Instead you could write an OR expression, as shown in the following code sample:

Performance Considerations

You should structure compound predicates to minimize the amount of work done. Regular expression matching in particular is an expensive operation. In a compound predicate, you should therefore perform simple tests before a regular expression; thus instead of using a predicate shown in the following example:

you should write

In the second example, the regular expression is evaluated only if the first clause is false.

Using Joins

In general, joins (queries that cross relationships) are also expensive operations, and you should avoid them if you can. When testing to-one relationships, if you already have—or can easily retrieve—the relationship source object (or its object ID), it is more efficient to test for object equality than to test for a property of the source object. Instead of writing the following:

it is more efficient to write:

If a predicate contains more than one expression, it is also typically more efficient to structure it to avoid joins. For example, @'firstName beginswith[cd] 'Matt' AND (ANY directreports.paygrade <= 7)' is likely to be more efficient than @'(ANY directreports.paygrade <= 7) AND (firstName beginswith[cd] 'Matt')' because the former avoids making a join unless the first test succeeds.

Structuring Your Data

In some situations, there may be tension between the representation of your data and the use of predicates. If you intend to use predicates in your application, the pattern of typical query operations may influence how you structure your data. In Core Data, although you specify entities and entity-class mapping, the levels that create the underlying structures in the persistent store are opaque. Nevertheless, you still have control over your entities and the properties they have.

In addition to tending to be expensive, joins may also restrict flexibility. It may be appropriate, therefore, to de-normalize your data. In general—assuming that queries are issued often—it may be a good trade-off to have larger objects, but for it to be easier to find the right ones (and so have fewer in memory).

Using Predicates with Cocoa Bindings

In OS X, you can set a predicate for an array controller to filter the content array. You can set the predicate in code (using setFilterPredicate:). You can also bind the array controller’s filterPredicate binding to a method that returns an NSPredicate object. The object that implements the method may be the File's Owner or another controller object. If you change the predicate, remember that you must do so in a key-value observing compliant way (see Key-Value Observing Programming Guide) so that the array controller updates itself accordingly.

You can also bind the predicate binding of an NSSearchField object to the filterPredicate of an array controller. A search field’s predicate binding is a multi-value binding, described in Binding Types.



Copyright © 2005, 2014 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2014-09-17

Examples of NSPredicate usage

Nspredicate Cheat Sheet Pdf

Created by Fluffy.es (Axel)Hosted on GitHub Pages

This page contains usage examples of NSPredicate, check here for Core Data usage examples 🔋

Cheat

Basic

Techniques

Examples (Entity’s property…)

Predicate Format and Arguments

Say for a predicate which select Person that have a name “Asriel” and 50 money :

The format is 'name %@ AND money %i'.

%@ and %i are the format specifiers, %@ will be substituted with an object (eg: String, date etc), whereas %i will be substituted with an integer.

The substitution happens as illustrated below, following the order from left to right :

%@ (object format specifier) will be replaced with “Asriel” and %i (integer format specifier) will be replaced with 50. Asriel and 50 is the arguments.

After substitution, the predicate will become 'name 'Asriel' AND money = 50' , meaning the NSPredicate will find for Person that have name Asriel and 50 money.


But why can’t I just use “name ‘Asriel’ AND money = 50” instead of having to use the format specifier thingy?

Yes of course you can! For simple filter which require a hardcoded value I recommend using it. The format specifier substitution is for variable value usually, like this :

String Format Specifier

You can check the full list in Apple official documentation. %@ is used for objects like String, Date, Array etc.

%K is used for Keypath (the property of the entity).

Nspredicate Cheat Sheet

Basic Comparison

Basic comparison symbol like , > , < etc.

Compound Comparison

Join two or more condition together with OR , AND.

Case insensitive Comparison

Nspredicate Cheat Sheet Template

For case insensitive comparison, put [c] after the comparison symbol.

Nspredicate Cheat Sheet

Reuse NSPredicate with substitution variable

As it is relatively time consuming for the app to parse the format string of the NSPredicate, we should try to reduce creating multiple NSPredicate and reuse similar NSPredicate as much as possible. We can use variable value in NSPredicate denoted by $ sign, and substitute its value by calling withSubstitutionVariables method.

You can use multiple variables like name BEGINSWITH $startingName AND money > $amount , then call withSubstitutionVariables(['startingName' : 'As', 'amount': 50]).

Using NSPredicate to filter Array of objects

Other than Core Data, we can also use NSPredicate to filter array of objects. The SELF in the format string means each individual element in the array.

Is included in an Array of values

Is not included in an Array of values

Begins with certain string

Contains certain string

Ends with certain string

Wildcard match with string

LIKE is used for wildcard match.

Wildcard match is used to match certain pattern of string, eg: to match img1.png , img10.png andimg100.png, we can use filename LIKE 'img*.png'. The * means zero or more characters between img and .png is accepted.

To match exactly one character, we can use ? , eg: filename LIKE 'img?.png' will match img1.png but not img10.png as it only take in one character between img and .png.

Regular Expression match with string

MATCHES is used for regular expression match.

Regular expression is used for complex string pattern matching. Swift uses ICU regular expression format.For learning regular expression, I recommend this tutorial.

Eg: filename MATCHES 'imgd{1,3}.png' will match filename with 1-3 digits between img and .png like img1.png, img10.png and img100.png but not img1000.png . Double backslash is used to escape the backslash character .





Comments are closed.