Usage of the predicate (NSPredicate) in iOS: (1) basic usage

Source: Internet
Author: User

Usage of the predicate (NSPredicate) in iOS: (1) basic usage

 

In iOS development, the system provides the NSPredicate class for us to perform some matching and filtering operations, which is very convenient. When this class is not used, we need to write code to compare some specific elements in two arrays. However, if we use this class, we only need three or four lines of code.

 

For demonstration, first define a person class

. H file

 

#import 
 
  @interface Person : NSObject@property (nonatomic, copy) NSString *name;@property (nonatomic, assign) NSInteger age;- (instancetype)initWithName:(NSString *)name                         Age:(NSInteger)age;+(Person *)personWithName: (NSString *)nsme                      Age: (NSInteger)age;@end
 

. M file

 

 

#import "Person.h"@implementation Person- (instancetype)initWithName:(NSString *)name Age:(NSInteger)age {    if (self = [super init]) {        _name = name;        _age = age;    }    return self;}+ (Person *)personWithName:(NSString *)nsme Age:(NSInteger)age {    Person *person = [[Person alloc] initWithName:nsme Age:age];    return person;}- (NSString *)description {    return [NSString stringWithFormat:@"name = %@, age = %ld",_name, _age];}@end

I have rewritten the description method in the implementation file to print the object attribute values when printing the filter results.

 

Then, introduce the person into the main file (cocoa is not used for demonstration), create 10 different person objects, and put them in the array.

 

// Create 10 person objects and add the array NSMutableArray * muArray = [NSMutableArray array]; for (int I = 0; I <10; I ++) {Person * person = [Person personWithName: [NSString stringWithFormat: @ "zhang % d", I] Age: I]; [muArray addObject: person];} NSLog (@ "muArray = % @", muArray );

 

OK. The preparation is complete. The main character is shown below.

NSPredicate is mainly used in two steps: Step 1: Define the predicate statement; Step 2: select different methods to execute the predicate statement as required.

First, let's define a predicate statement. when defining a predicate statement, we will introduce the syntax of the predicate.

1) Comparison Operators

 

/** Comparison operator **>: greater than * <: less than *> =: greater than or equal to * <=: less than or equal to * =, =: equal *! =, <>: Not equal to * between: The expression on the left is equal to the value of the expression on the right or between them. The right side is a series of two values with the specified upper limit and lower limit (a series with the specified order ). For example, 1 BETWEEN {0, 33}, or $ input between {$ LOWER, $ UPPER }. ** // Example: the age attribute is greater than 3 years old. Note: The Key Path cannot be enclosed by single quotation marks. Otherwise, the NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "age> 3"];
2) logical operators

 

 

/** Logical operator * and/&: and * or/|: or * not /! : Not ** // example: if the age is greater than three years old or the name is "zhang1", note that the string value must be enclosed in single quotes. Otherwise, an error is reported. The error message is: this class is not key value coding-compliant for the key zhang1. NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "age> 3 | name = 'hang1'"];

3) Relational operators

 

 

/** Relational operation ** ANY, SOME: specifies ANY element in the following expressions. For example, ANY children. age <18. * ALL: ALL elements in the following expressions. For example, ALL children. age <18. * NONE: Specifies the elements not in the following expressions. For example, NONE children. age <18. Logically, it is NOT (ANY ...). * IN: equals to the SQL IN operation. The expression on the left must appear IN the specified set on the right. For example, name IN {'ben', 'melissa ', 'Nick '}. ** // Example: in Keyword: the keyword on the left must contain the NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "name in {'hangzhou1 ', 'hangzhou4'} "];

4) Array Operations

 

 

/** Array operation * array [index]: Specifies the element at a specific index in the array. * Array [FIRST]: Specifies the FIRST element in the array. * Array [LAST]: Specifies the LAST element in the array. * Array [SIZE]: Specifies the SIZE of the array. **/

The above is the definition of the predicateWithFormat class.

 

Next, go to step 2: Execute the predicate statement.

1) filter objects as Arrays: Use-(void) filterUsingPredicate :( NSPredicate *) predicate; filter variable arrays to filter out non-conforming variables. -(NSArray *) filteredArrayUsingPredicate :( NSPredicate *) predicate; filters out immutable arrays and forms qualified elements into a new array for return.
2) use-(BOOL) evaluateWithObject (id) object to filter a single object and send this method to the predicate object. The parameter is the filtered object. It is commonly used in combination with regular expressions.

The following describes the three methods described above.

A),-(void) filterUsingPredicate :( NSPredicate *) predicate; filter variable Arrays

 

// 1. Create 10 person objects and add the array NSMutableArray * muArray = [NSMutableArray array]; for (int I = 0; I <10; I ++) {Person * person = [Person personWithName: [NSString stringWithFormat: @ "zhang % d", I] Age: I]; [muArray addObject: person];} NSLog (@ "muArray = % @", muArray );
// 2. Define the predicate statement: the age attribute is greater than 3 years old. Note: The Key Path cannot be enclosed by single quotation marks. Otherwise, the NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "age> 3"];
// 3. filter the variable array [muArray filterUsingPredicate: predicate]; NSLog (@ "variable array filtered result % @", muArray );
The printed result is:

 

 

11:58:23. 126 NSPredicate [3183: 277528] Results After variable array filtering ("name = zhang4, age = 4", "name = zhang5, age = 5", "name = zhang6, age = 6 "," name = zhang7, age = 7 "," name = zhang8, age = 8 "," name = zhang9, age = 9 ")

B),-(NSArray *) filteredArrayUsingPredicate :( NSPredicate *) predicate; filter immutable arrays and form a new array of qualified elements to return.

 

 

//-(NSArray *) filteredArrayUsingPredicate :( NSPredicate *) predicate; filter immutable arrays, returns NSArray * beforeFilterArray = [NSArray arrayWithArray :( NSArray *) muArray]; NSArray * afterFilterArray = [beforeFilterArray encoding: predicate]; NSLog (@ "immutable array filtering result % @", afterFilterArray );

The printed result is as follows:

 

 

11:58:23. 126 NSPredicate [3183: 277528] immutable array filtering results ("name = zhang4, age = 4", "name = zhang5, age = 5", "name = zhang6, age = 6 "," name = zhang7, age = 7 "," name = zhang8, age = 8 "," name = zhang9, age = 9 ")

C),-(BOOL) evaluateWithObject :( id) object; filter each element in the array

 

 

NSMutableArray * matchObjArray = [NSMutableArray array]; for (Person * item in muArray) {// A. Determine whether the condition is met. // judgment statement: evaluateWithObject, if the filter condition is met, yes if ([predicate evaluateWithObject: item]) {[matchObjArray addObject: item] ;}} NSLog (@ "the object that meets the filter condition is: % @", matchObjArray );

The filtering result is:

 

 

11:58:23. 125 NSPredicate [3183: 277528]: ("name = zhang4, age = 4", "name = zhang5, age = 5", "name = zhang6, age = 6 "," name = zhang7, age = 7 "," name = zhang8, age = 8 "," name = zhang9, age = 9 ")

Summary: The above three methods can execute predicate phrases. If you filter array elements, we use:-(void) filterUsingPredicate :( NSPredicate *) predicate,-(NSArray *) filteredArrayUsingPredicate :( NSPredicate *) predicate; it is more convenient to use-(BOOL) evaluateWithObject :( id) object if only one object is judged.

 





 

 

 




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.