Brief Introduction to NSPredicate, nspredicate
Several main calculation methods in NSPredicate
1. Comparison operators>, <, =, >=, <=, and ,! =
Example: @ "number> = 99"
2. logical operators: AND, OR, and not operators calculate AND, OR, AND non-results.
3. Range operators: IN and
Example: @ "number BETWEEN {1, 5 }"
@ "Address IN {'shanghai', 'nanjing '}"
4. string itself: SELF
Example: @ "SELF = 'apple '"
5. String-related: BEGINSWITH, ENDSWITH, and CONTAINS
Example: @ "name CONTAIN [cd] 'ang '" // contains a string
@ "Name BEGINSWITH [c] 'sh'" // starts with a string
@ "Name ENDSWITH [d] 'ang '" // end with a string
Note: [c] is case-insensitive, and [d] is case-insensitive. That is, there is no accent. [cd] is case-insensitive and does not distinguish between pronunciation symbols.
6. wildcard: LIKE
For example, @ "name LIKE [cd] '* er *'" // * Indicates a wildcard, and Like also accepts [cd].
@ "Name LIKE [cd] '??? Er *'"
7. Regular Expression: MATCHES
For example, NSString * regex = @ "^ A. + e $"; // starts with A and ends with e.
@ "Name MATCHES % @", regex
Use NSPredicate to filter the differences between two Arrays
NSArray* array = @[@"aa",@"bb"];NSArray* array2 = @[@"aa",@"bb",@"cc",@"dd"];NSPredicate* thePredicate = [NSPredicate predicateWithFormat:@"NOT(SELF in %@)",array];NSArray* arr3 = [array2 filteredArrayUsingPredicate:thePredicate];NSLog(@"%@",arr3);
The above code output result arr3 = {@ "cc", @ "dd "}
Use NSPredicate to Filter Arrays
NSString * regex = @ "^ A. + e $"; // A character that starts with A and ends with e. NSPredicate * pre = [NSPredicate predicateWithFormat: @ "self matches % @", regex]; if ([pre evaluateWithObject: @ "Apple"]) {
NSLog (@ "YES ");
}else{
NSLog (@ "NO ");
}
Other NSPredicate instructions, precautions, and skills
Dynamic attribute name
NSPredicate *p = [NSPredicate predicateWithFormat:@"name = %@", @"name1"];
Obviously there is no problem with the code, but this is not the best method. I suggest writing it as follows:
NSPredicate *preTemplate = [NSPredicate predicateWithFormat:@"name==$NAME"];
NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:
@"name1", @"NAME",nil];
NSPredicate *pre=[preTemplate predicateWithSubstitutionVariables: dic];
This may make the code logic clearer.
When the filter condition fields are dynamic
NSString *key = @"name"; NSString *value = @"name1"; NSPredicate *p = [NSPredicate predicateWithFormat:@"%@ = %@", key, value];
Then, when you execute the third line, the code will report an error!
No logic error !!! Why?
NSPredicate must automatically add quotation marks, so the final format should be @ "'name' = 'name1 '". Obviously not. What you need to do is:
NSPredicate *p = [NSPredicate predicateWithFormat:@"%K = %@", key, value];