Use of predicate nspredicate in IOS

Time:2021-12-31

What is nspredicate?

The nspredicate class is used to define the acquisition of logical condition constraints or filter search in memory. Generally speaking, predicates describe the attributes of things. In IOS, it is mainly used for query and retrieval, such as coredata data query, array and other collection type filtering.

  • Classification of predicates: comparative predicates and compound predicates
  • Comparison predicate: the comparison predicate describes the qualified attribute state by using comparison operators;
  • Compound predicate: used to combine multiple comparison predicate expressions, such as intersection, union and complement;

We all need to define a predicate expression when using nspredicate, and this expression must return the bool value.

  • How nspredicate is created
  1. Create predicates by formatting strings;
  2. Create predicates through templates;
  3. Create predicates through code;
  • Predicate formatting syntax table
operator Meaning interpretation
==,= Determine whether the left and right expressions are equal
!=, <> Judge whether the two expressions on the left and right are not equal
>=,=> Judge whether the value on the left is greater than or equal to the value on the right
<=,=< Judge whether the value on the left is less than or equal to the value on the right
> Judge whether the value on the left is greater than the value on the right
< Judge whether the value on the left is less than the value on the right
BETWEEN The left side must be in the interval of the right set. Between {lower limit, upper limit}
AND,&& Logical and. The result is yes only when the value of both expressions is required to be yes
OR,ll Logical or, when one of the expressions is required to be yes, the result is yes
NOT,! Logical non, invert the original expression
BEGINSWITH Checks whether the string starts with the specified string
ENDSWITH Checks whether the string ends with the specified string
CONTAINS Checks whether a string contains the specified string
LIKE Check whether the string matches the specified string template, which can be compared with * and? Wildcards such as can be used
MATCHES Checks whether the string matches the specified regular expression
ANY,SOME If any element in the collection meets the condition, it returns yes
ALL Returns Yes only if all elements in the collection meet the conditions
NONE Returns yes if none of the elements in the collection meet the criteria
IN The expression on the left exists in the set on the right and returns yes
array[index] Returns the element at index in the array
array[FIRST] Returns the first element in the array
array[LAST] Returns the last element in the array
array[SIZE] Returns the number of elements in the array
FALSE,NO Represents logical false
TRUE,YES Stands for logical truth
NULL,NIL Represents a null value
SELF Represents the object itself that needs to be verified
“str”,’str’ Represents a string, which needs to be escaped when ” is used
{‘a’,’b’,’c’ } Representative array
FALSEPREDICATE Predicate that always returns yes
TRUEPREDICATE Predicate that always returns no
  • String passing ignores case and accent

When using predicate retrieval, if the string comparison operators need to be case insensitive and accent insensitive, use the [C], [D] options after these string operators. Where [C] means case insensitive, [D] means accent insensitive, [CD] means case insensitive and accent insensitive. It needs to be written after the string comparison operator, such as: name like [CD] ‘string’

  • Reserved words: both case and upper case can be used, and uppercase is recommended

AND、OR、IN、NOT、ALL、ANY、SOME、NONE、LIKE、CASEINSENSITIVE、CI、MATCHES、CONTAINS、BEGINSWITH、ENDSWITH、BETWEEN、NULL、NIL、SELF、TRUE、YES、FALSE、NO、FIRST、LAST、SIZE、ANYKEY、SUBQUERY、CAST、TRUEPREDICATE、FALSEPREDICATE

Creation of nspredicate

  • Create predicates by formatting strings:
  1. Common methods:
  // Parse predicateFormat and return an appropriate predicate
 + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat argumetArray:(nullable NSArray *)arguments;
 + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;
 + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat arguments:(va_list)argList;
  1. Use example:
NSArray * test = @[@"Herbie",@"Badger",@"Elvis",@"Phoenix",@"Streaker"];
//Retrieves an object with string attribute length 5
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"length = 5"];
NSArray * result = [test filteredArrayUsingPredicate:predicate];
//Print results
// @[@"Elvis"]
  1. explain:

There are many ways to create predicates by formatting strings. You can directly use strings, such as “length = 5”, or use placeholders such as% @,% D and% k to replace them with the actual value of variables at run time. Here we focus on% K and% k to pass in the attribute name. Why not use% @ when setting the attribute name? Because% @ will be automatically added with quotation marks by the parser during parsing, the attribute name does not need quotation marks, so you choose to use% k to set the attribute name and% @ to set the attribute value.

NSString *key = @"length";
NSString *value = @"5";
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"%k = 5", key];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"%k = %@", key, value];
  • Create verbs from templates:
    Create predicate retrieval through the template. There are only key names (attribute names) and no key values (attribute values) in the predicate template. The key values are configured in the dictionary and provided to the template for use. The $symbol is used to match the values in the template and the dictionary.
  1. Common methods:
- (instancetype)predicateWithSubstitutionVariables:(NSDictionary<NSString *, id> *)variables;
  1. Use example:
NSDictionary *valueDict = [NSDictionary dictionaryWithObjectsAndKeys:@5, @"LENGTH", nil];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"length = $LENGTH"];
NSArray * test = @[@"Herbie",@"Badger",@"Elvis",@"Phoenix",@"Streaker"];
NSArray * results = [test filteredArrayUsingPredicate:predicate];
//Print results
// @[@"Elvis"]
  • Create predicates from code:
    The method of creating predicate objects using code is more complex than the above two methods, and is similar to the method of creating AutoLayout constraints through code. Create predicate objects through nscomparisonpredicate class;
  1. Implementation code
//Create the left expression object corresponding to the key
NSExpression *leftExpression = [NSExpression expressionForKeyPath:@"length"];
//Create the right expression object corresponding to the value
NSExpression *rightExpression = [NSExpression expressionForConstantValue:@5];
//Create comparison predicate object
NSComparisonPredicate *predicate = [NSComparisonPredicate predicateWithLeftExpression:leftExpression rightExpression:rightExpression modifier:NSDirectPredicateModifier type:NSEqualToPredicateOperatorType options:NSCaseInsensitivePredicateOption];
NSArray * test = @[@"Herbie",@"Badger",@"Elvis",@"Phoenix",@"Streaker"];
NSArray * results = [test filteredArrayUsingPredicate:predicate];
  1. Nscomparisonpredicatemodifier is used to modify the setting of comparison conditions

Nsdirectpredictemodifier, / / perform comparison directly
Nsallpredictemodifier, / / used for arrays or collections. Only when all internal elements pass validation can the collection pass
Nsanypredictemodifier, / / the same as an array or collection. When an internal element is satisfied, the collection passes the verification
Note: nsallpredictemodifier and nsanypredictemodifier enumerations are mainly applicable to the validation of array and collection type data. All will validate all elements in the array or collection, and the array or collection will pass the validation only after all elements pass. Any will pass the validation as long as one element passes the validation;

  1. The nspredicateoperatortype enumeration is used to set the operator type

Nslessthanpredicteoperatortype = 0, / / less than
Nslessthanorequaltopredicteoperatortype, / / less than or equal to
Nsgreaterthan predicateoperatortype, / / greater than
Nsgreaterthanorequaltopredicteoperatortype, / / greater than or equal to
Nsequaltopredicateoperatortype, / / equal to and the same
Nsnoteequaltopredicateoperatortype, / / not equal to or the same
Nsmatchspredicateoperatortype, / / regular expression matching
Nslikepredicteoperatiortype, / / like wildcard
Nsbeginswithpredicateoperatortype, / / string starts with a string
Nsendswithpredicateoperatortype, / / string ends with a character
Nsinpredicateoperatortype, / / the expression on the left appears in the collection on the right
Nscustomeselectorpredicateoperatiortype, / / use a custom function to verify
Nscontainspredicateoperatortype, / / the set on the left includes the element on the right
Nsbetweenpredicateoperatortype, / / the value of the expression on the left is in the range on the right

  1. The nscomparisonpredicateoptions enumeration is used to set the method of comparison

Nscaseinsensitivepredicteoption, / / case insensitive
Nsdiacriticinspectivepredicateoption, / / does not distinguish pronunciation symbols
Nsnormalizedpredicateoption, / / preprocess strings before comparison, replace the above two options, and optimize them

  1. Nscompoundpredict class
    This class is also a subclass of nspredicate. It is used to combine multiple predicate objects for retrieval.
//Initializing compound predicates
- (instancetype)initWithType:(NSCompoundPredicateType)type subpredicates:(NSArray<NSPredicate *> *)subpredicates;
//Fast creation and operation
+ (NSCompoundPredicate *)andPredicateWithSubpredicates:(NSArray<NSPredicate *> *)subpredicates;
//Quick creation or operation
+ (NSCompoundPredicate *)orPredicateWithSubpredicates:(NSArray<NSPredicate *> *)subpredicates;
//Quickly create non operations
+ (NSCompoundPredicate *)notPredicateWithSubpredicate:(NSPredicate *)predicate;

Actual use

  • Array collection filtering method:
@interface NSArray<ObjectType> (NSPredicateSupport)
- (NSArray<ObjectType> *)filteredArrayUsingPredicate:(NSPredicate *)predicate; 
@end
@interface NSMutableArray<ObjectType> (NSPredicateSupport)
- (void)filterUsingPredicate:(NSPredicate *)predicate;
@end
@interface NSSet<ObjectType> (NSPredicateSupport)
- (NSSet<ObjectType> *)filteredSetUsingPredicate:(NSPredicate *)predicate;
@end
@interface NSMutableSet<ObjectType> (NSPredicateSupport)
- (void)filterUsingPredicate:(NSPredicate *)predicate;
@end
@interface NSOrderedSet<ObjectType> (NSPredicateSupport)
- (NSOrderedSet<ObjectType> *)filteredOrderedSetUsingPredicate:(NSPredicate *)p;
@end
@interface NSMutableOrderedSet<ObjectType> (NSPredicateSupport)
- (void)filterUsingPredicate:(NSPredicate *)p;
@end
  • Verification code
    Demo

Recommended Today

Could not get a resource from the pool when the springboot project starts redis; nested exception is io. lettuce. core.

resolvent: Find your redis installation path: Start redis server Exe After successful startup: Restart project resolution. ———————————————————————->Here’s the point:<——————————————————————- Here, if you close the redis command window, the project console will report an error. If you restart the project, the same error will be reported at the beginning, The reason is: It is inconvenient to […]