In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use NSPredicate in iOS. It is very detailed and has a certain reference value. Friends who are interested must finish it!
I. introduction
In the interpretation of modern Chinese, predicates are words used to describe or judge the nature, characteristics or relationship between objects. Popularly speaking, it describes the properties of things. In the iOS development Cocoa framework, there is a NSPredicate class, which is usually called a predicate class, and its main function is to help query and retrieval in Cocoa, but it should be noted that in essence, predicates do not provide query and retrieval support, it is a way to describe query retrieval conditions, just like the more standard and general regular expressions.
The predicates provided by NSPredicate can be divided into two categories: comparative predicates and compound predicates.
Comparison predicate: the comparison predicate describes the attribute state of the condition by using the comparison operator.
Compound predicate: compound predicate is used to combine the results of multiple comparative predicates, taking intersection, union, or complement.
For comparison predicates, accurate comparisons can be described or fuzzy comparisons can be made by scope, inclusion, etc. It is important to note that any Cocoa class object can support predicates, but this class needs to implement the key-value coding (key-value-coding) protocol.
2. Application analysis of NSPredicate class.
NSPredicate provides methods for creating and parsing predicate objects, which are also the base class for predicate classes in Cocoa. In our daily development, the NSPredicate class is also used the most frequently.
There are three ways to create a predicate object: create a predicate by formatting a string, create a predicate directly through code, and create a predicate through a template. NSPredicate provides the following functions for initialization:
/ / initialize the predicate object by formatting the string + (NSPredicate *) predicateWithFormat: (NSString *) predicateFormat argumentArray: (nullable NSArray *) arguments;+ (NSPredicate *) predicateWithFormat: (NSString *) predicateFormat,...; + (NSPredicate *) predicateWithFormat: (NSString *) predicateFormat arguments: (va_list) argList
Initializing predicates using formatted strings is very flexible, but it should be noted that the syntax of predicate strings is not the same as regular expressions, which will be described in detail later. Here is an example of predicate retrieval:
/ / retrieve the object NSPredicate * predicate = [NSPredicate predicateWithFormat:@ "length = 5"] with attribute length 5; / / for the string in this array, retrieve the element NSArray * test = @ [@ "sda", @ "321", @ "sf12", @ "dsdwq1", @ "swfas"]; NSArray * result = [test filteredArrayUsingPredicate:predicate]; / / will print @ [@ "swfas"] NSLog (@ "% @", result)
In fact, you can also construct a formatted string like the NSLog function, using% @,% d, and other formatting characters to replace it with the actual value of the variable at run time. It should also be noted that predicate sentences created by this formatted string are not syntactically checked, and incorrect syntax can lead to run-time errors, so be careful. There is a small detail to note. When formatting, you do not need to add quotation marks if you are using variables, and the parser will help you add them. If you use constants, escape characters should be used, for example:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@ "name =% @ & & age =\" 25\ ", name]
For attribute names, if you also need to format them, you should be careful not to use the% @ symbol, which is automatically quoted by the parser when parsing. You can use% K, as shown in the example:
NSString * key = @ "length"; NSPredicate * predicate = [NSPredicate predicateWithFormat:@ "% K = 5", key]; NSArray * test = @ [@ "sda", @ "321", @ "sf12", @ "dsdwq1", @ "swfas"]; NSArray * result = [test filteredArrayUsingPredicate:predicate]; / / will print @ [@ "swfas"] NSLog (@ "% @", result)
Creating predicate objects through templates is also a very common way. Unlike formatting strings, there are only key names and no key values in predicate templates, which need to be provided in a dictionary, for example:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@ "length = $LENGTH"]; predicate = [predicate predicateWithSubstitutionVariables:@ {@ "LENGTH": @ 5}]; NSArray * test = @ [@ "sda", @ "321", @ "sf12", @ "dsdwq1", @ "swfas"]; NSArray * result = [test filteredArrayUsingPredicate:predicate]; / / will print @ [@ "swfas"] NSLog (@ "% @", result)
Other properties and methods in NSPredicate are parsed as follows:
/ / create a predicate object that always passes (YES) or fails (NO) / * if you create a validated pass, any retrieval will be returned successfully, otherwise any retrieval will fail without returning any object * / + (NSPredicate *) predicateWithValue: (BOOL) value;// custom implementation retrieval function / *
For example, the previous example can also be written like this.
NSPredicate* predicate = [NSPredicate predicateWithBlock: ^ Bool (id _ Nullable evaluatedObject, NSDictionary * _ Nullable bindings) {if ([evaluatedObject length] = = 5) {return YES;} return NO;}]; * / + (NSPredicate*) predicateWithBlock: (BOOL (^) (id _ Nullable evaluatedObject, NSDictionary * _ Nullable bindings) block;// format string attribute @ property (readonly, copy) NSString * predicateFormat / / when the predicate template is used for object creation, this function is used to set the variable substitution in the predicate template-(instancetype) predicateWithSubstitutionVariables: (NSDictionary *) variables;// to check whether an Object object can be validated by verifying-(BOOL) evaluateWithObject: (nullable id) object; / / validating the object with the predicate template-(BOOL) evaluateWithObject: (nullable id) object substitutionVariables: (nullable NSDictionary *) bindings
Third, create predicate objects through code
We said earlier that there are three ways to create a predicate object, two of which we have already introduced, and creating a predicate object directly through code is the most complex. Creating predicate objects through code is very similar to creating Autolayout constraints through code. As we explained earlier, predicates actually use expressions to validate objects, and to create predicates with code is to create expressions with code.
1. Let's take a look at the NSComparisonPredicate class.
This class is a subclass of NSPredicate and is used to create predicates of comparison types. For example, use the following code to rewrite the above example:
/ / create the left expression object corresponding to the key NSExpression * left = [NSExpression expressionForKeyPath:@ "length"]; / / create the right expression object corresponding to the value NSExpression * right = [NSExpression expressionForConstantValue: [NSNumber numberWithInt:5]]; / / create the comparison predicate object here set to be strictly equal to NSComparisonPredicate * pre = [NSComparisonPredicate predicateWithLeftExpression:left rightExpression:right modifier:NSDirectPredicateModifier type:NSEqualToPredicateOperatorType options:NSCaseInsensitivePredicateOption] NSArray * test = @ [@ "sda", @ "321", @ "sf12", @ "dsdwq1", @ "swfas"]; NSArray * result = [test filteredArrayUsingPredicate:pre]; / / will print @ [@ "swfas"] NSLog (@ "% @", result)
The modification settings used by NSComparisonPredicateModifier for conditions are enumerated as follows:
Typedef NS_ENUM (NSUInteger, NSComparisonPredicateModifier) {NSDirectPredicateModifier = 0, / / compare operation NSAllPredicateModifier directly, / / for arrays or collections only if all internal elements are validated, the collection passes NSAnyPredicateModifier / / is the same as the array or collection when there is an element inside.
With regard to NSAllPredicateModifier and NSAnyPredicateModifier, these two enumerations are used specifically for the validation of array or collection type objects. ALL validates all elements, all of which pass the latter array or collection, while ANY validates an array or collection as long as one element is validated, for example:
NSPredicate * pre = [NSPredicate predicateWithFormat:@ "ALL length = 5"]; NSArray * test = @ [@ [@ "aaa", @ "aa"], @ [@ "bbbb", @ "bbbbb"], @ [@ "ccccc", @ "ccccc"]; NSArray * result = [test filteredArrayUsingPredicate:pre]; / will print @ [@ [@ "ccccc", @ "ccccc"] NSLog (@ "% @", result)
The NSPredicateOperatorType enumeration is used to set the operator type, as follows:
Typedef NS_ENUM (NSUInteger, NSPredicateOperatorType) {NSLessThanPredicateOperatorType = 0, / / less than NSLessThanOrEqualToPredicateOperatorType, / / less than or equal to NSGreaterThanPredicateOperatorType, / / greater than NSGreaterThanOrEqualToPredicateOperatorType, / / greater than or equal to NSEqualToPredicateOperatorType, / / equal to NSNotEqualToPredicateOperatorType, / / not equal to NSMatchesPredicateOperatorType, / / regular matching NSLikePredicateOperatorType, / / Like match is similar to SQL NSBeginsWithPredicateOperatorType, / / the expression on the left begins with the expression on the right NSEndsWithPredicateOperatorType / / the expression on the left ends with the expression on the right NSInPredicateOperatorType, / / the expression on the left appears in the collection on the right NSCustomSelectorPredicateOperatorType,// uses custom functions to validate NSContainsPredicateOperatorType, / / the collection on the left includes the element on the right NSBetweenPredicateOperatorType / / the value of the expression on the left is in the range of 1 BETWEEN {0,33}}
The NSComparisonPredicateOptions enumeration is used to set the comparison method, as follows:
/ / if you do not need to specify this enumerated value, you can also pass 0typedef NS_OPTIONS (NSUInteger, NSComparisonPredicateOptions) {NSCaseInsensitivePredicateOption = 0x01, / / case-insensitive NSDiacriticInsensitivePredicateOption = 0x02 / undistinguished pronunciation NSNormalizedPredicateOption / / replace the above two options}
2.NSExpression class
The NSExpression class provides creation expressions, and here are some easy-to-understand methods:
/ / create the expression + (NSExpression *) expressionWithFormat: (NSString *) expressionFormat argumentArray: (NSArray *) arguments;+ (NSExpression *) expressionWithFormat: (NSString *) expressionFormat,...; + (NSExpression *) expressionWithFormat: (NSString *) expressionFormat arguments: (va_list) argList;// create the always bright expression + (NSExpression *) expressionForConstantValue: (nullable id) obj directly through the object / / when creating variable expression validation, replace + (NSExpression *) expressionForVariable: (NSString *) string; / / combine multiple expressions into one + (NSExpression *) expressionForAggregate: (NSArray *) subexpressions;+ (NSExpression *) expressionForUnionSet: (NSExpression *) left with: (NSExpression *) right;+ (NSExpression *) expressionForIntersectSet: (NSExpression *) left with: (NSExpression *) right;+ (NSExpression *) expressionForMinusSet: (NSExpression *) left with: (NSExpression *) right + (NSExpression *) expressionForSubquery: (NSExpression *) expression usingIteratorVariable: (NSString *) variable predicate: (NSPredicate *) predicate;// builds predefined functions for expression objects through predefined functions and parameter arrays see dev development document + (NSExpression *) expressionForFunction: (NSString *) name arguments: (NSArray *) parameters
3.NSCompoundPredicate class
This class, which is also a subclass of the NSPredicate class, uses logical relationships to combine multiple predicate objects, parsed as follows:
/ initialize the object / * typedef NS_ENUM (NSUInteger, NSCompoundPredicateType) {NSNotPredicateType = 0, / / take non-NSAndPredicateType, / / and operation NSOrPredicateType, / / or operation}; * /-(instancetype) initWithType: (NSCompoundPredicateType) type subpredicates: (NSArray *) subpredicates;// Rapid creation and Operation + (NSCompoundPredicate *) andPredicateWithSubpredicates: (NSArray *) subpredicates;// Rapid creation or Operation + (NSCompoundPredicate *) orPredicateWithSubpredicates: (NSArray *) subpredicates / / quickly create non-operational + (NSCompoundPredicate *) notPredicateWithSubpredicate: (NSPredicate *) predicate
IV. Several scenarios for the use of predicates
Predicates are mainly used to verify the filtering of objects, arrays, and collections. Object validation is described earlier, with regard to data and collection filtering functions, the categories are as follows:
@ interface NSArray (NSPredicateSupport) / / the immutable array returns a new array after using the filter-(NSArray *) filteredArrayUsingPredicate: (NSPredicate *) predicate;@end@interface NSMutableArray (NSPredicateSupport) / / the variable array can be filtered directly-(void) filterUsingPredicate: (NSPredicate *) predicate;@end@interface NSSet (NSPredicateSupport) / / the immutable set returns the new collection-(NSSet *) filteredSetUsingPredicate: (NSPredicate *) predicate @ end@interface NSMutableSet (NSPredicateSupport) / / variable sets can be filtered directly-(void) filterUsingPredicate: (NSPredicate *) predicate;@end@interface NSOrderedSet (NSPredicateSupport)-(NSOrderedSet *) filteredOrderedSetUsingPredicate: (NSPredicate *) pscape endurance interface NSMutableOrderedSet (NSPredicateSupport)-(void) filterUsingPredicate: (NSPredicate *) pleading end
V. Overview of formatted grammar of predicates
The syntax for formatting string rules in predicates is listed below.
Grammatical rule meaning = left equal to right = = left equal to right, consistent with = consistent with left greater than equal to right = > left greater than equal to right and > = consistent with
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.