NSPredicate Cheatsheet, Basic, compound, Aggregate, String, comparison operators
Format string summary
@"attributeName == %@"
@"%K == %@"
@"%name IN $NAME_LIST"
@"'name' IN $NAME_LIST"
[NSPredicate predicateWithFormat: @"title == %@", @"minecraft"]
BEGINSWITH
CONTAINS
ENDSWITH
LIKE
MATCHES
[NSPredicate predicateWithFormat: @"name BEGINSWITH 'm'"]
Basic comparisons
=,==
>=,=>
<=,=<
>
<
!=,<>
IN
BETWEEN
[NSPredicate predicateWithFormat: @"expenses BETWEEN {200, 400}"]
Basic compound predicates
A
ND,&&
OR,||
NOT,!
[NSPredicate predicateWithFormat: @"age == 40 AND price > 67"]
Aggregate operators
A
NY,SOME
ALL
NONE
[NSPredicate predicateWithFormat: @"ALL expenses > 1000"]
Keypath collection queries
@avg
@count
@min
@max
@sum
[NSPredicate predicateWithFormat: @"expenses.@avg.doubleValue < 200"]
Object, array, and set operators
@distinctUnionOfObjects
@unionOfObjects
NSArray *payees = [transactions valueForKeyPath:@"@distinctUnionOfObjects.payee"]
@distinctUnionOfArrays
@unionOfArrays
These must be run on an array of arrays. For example if you had:
NSArray *arrayOfTransactions = [[Array of transactions], [Array of transactions]]
NSArray *payees = [arrayOfTransactions valueForKeyPath:@"@distinctUnionOfObjects.payee"]
@distinctUnionOfSets
Array operations
array[index]
array[FIRST]
array[LAST]
array[SIZE]
Let’s say we have a person with many dogs. index
should be replaced with a number which will return the dog that you want to check against. Here we’re checking if the first dog’s age is 5.
[NSPredicate predicateWithFormat: @"dogs[0].age = 5"]
Here we’re checking if a person has 3 dogs
[NSPredicate predicateWithFormat: @"dogs[SIZE] = 3"]
Subqueries
Iterates through the collection to return qualifying queries
Collection - array or set of objects
variableName - variable that represents an iterated object
predicateFormat - predicate that runs using the variableName
[NSPredicate predicateWithFormat: @"SUBQUERY(tasks, $task, $task.completionDate != nil AND $task.user = 'Alex') .@count > 0"]
Assume this was run on an array of projects. It will return projects with tasks that were not completed by user Alex
Comments
Post a Comment