The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.
Language
- Swift
- Objective-C
SDKs
- iOS 3.0+
- macOS 10.4+
- tvOS 3.0+
- watchOS 2.0+
Overview
You use predicates to represent logical conditions, used for describing objects in persistent stores and in-memory filtering of objects. Although it is common to create predicates directly from instances of NSComparisonPredicate, NSCompoundPredicate, and NSExpression, you often create predicates from a format string which is parsed by the class methods on NSPredicate. Examples of predicate format strings include:
Simple comparisons, such as
grade == "7"orfirstName like "Shaffiq"Case and diacritic insensitive lookups, such as
name contains[cd] "itroen"Logical operations, such as
(firstName like "Mark") OR (lastName like "Adderley")In macOS 10.5 and later, you can create between predicates such as
date between {$YESTERDAY, $TOMORROW}.
You can create predicates for relationships, such as:
group.name like "work*"ALL children.age > 12ANY children.age > 12
You can create predicates for operations, such as @sum.items.price < 1000. For a complete syntax reference, refer to the Predicate Programming Guide.
You can also create predicates that include variables, so that the predicate can be pre-defined before substituting concrete values at runtime. In OS X v10.4, for predicates that use variables, evaluation is a two step process (see withSubstitutionVariables(_:) and evaluate(with:)). In macOS 10.5 and later, you can use evaluate(with:substitutionVariables:), which combines these steps.