Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the process of getting started with the predicate NSPredicate in iOS

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shows you how to get started with the predicate NSPredicate in iOS. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Preface

First of all, we need to know what the predicate is. Let's look at the official explanation:

The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.

The NSPredicate class is used to define the acquisition of logical conditional constraints or filtered searches in memory. Predicates can be used to represent logical conditions that describe object filtering that persists in memory. In fact, it means: I am a filter, those who do not meet the requirements are out of here.

1. The basic grammar of NSPredicate

We use a language, whether it is a foreign language or a computer language, which always starts with grammar, so that we can correctly grasp the logic. So let's start with grammar. In this part, we are only concerned with the use of its grammar.

Whenever we use a predicate (NSPredicate), we need to define a predicate expression for the predicate, and the expression must be a value that returns BOOL. Predicate expressions consist of expressions, operators, and values.

1. Comparison operator

The comparison operator is as follows

=, = =: judge whether two expressions are equal. In the predicate, both = and = = have the same meaning to judge, but there is no assignment.

NSNumber * testNumber = @ 123; NSPredicate * predicate = [NSPredicate predicateWithFormat:@ "SELF = 123"]; if ([predicate evaluateWithObject:testNumber]) {NSLog (@ "testString:%@", testNumber);}

We can see that the output is as follows:

2016-01-07 11 12 27.281 PredicteDemo [4130 V 80412] testString:123

> =, = >: determines whether the value of the expression on the left is greater than or equal to the value of the expression on the right = 18:00 before returning YES. IN: equivalent to the IN operator in the SQL statement, YES is returned only if the left expression or value appears in the collection on the right. Let's take a look at an example.

NSArray * filterArray = @ [@ "ab", @ "abc"]; NSArray * array = @ [@ "a", @ "ab", @ "abc", @ "abcd"]; NSPredicate * predicate = [NSPredicate predicateWithFormat:@ "NOT (SELF IN% @)", filterArray]; NSLog (@ "% @", [array filteredArrayUsingPredicate:predicate])

The purpose of the code is to remove the same elements in array and filterArray, and the output is as follows:

2016-01-07 13 PredicteDemo 1715 43.669 PredicteDemo [6701 136206] (a, abcd)

Array [index]: returns the element array at the index index in the array array [FIRST]: returns the first element in the array array, array [LAST]: returns the last element in the array array, array [SIZE]: returns the number of elements in the array array

5. Direct quantity

The following direct quantities can be used in predicate expressions

FALSE, NO: represents logical false TRUE, YES: represents logical true NULL, NIL: represents null SELF: represents the object being judged itself "string" or 'string': represents string array: same as in c, for example: {' one', 'two',' three'}. Numeric values: including certificates, decimals and scientific numerals in the form of hexadecimal numbers: octal numbers starting with 0x: binary numbers starting with 0o: numbers starting with 0b

6. Reserved word

The following words are reserved (regardless of case)

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

Note: although both uppercase and lowercase are acceptable, it is more recommended to use uppercase to represent these reserved words

Second, the usage of predicates

1. Define predicate

Generally, we use the following methods to define a predicate

NSPredicate * predicate = [NSPredicate predicateWithFormat:]

Let's use a few simple examples to see how it should be used:

First we need to define a model because we need to use it in the example

ZLPersonModel.h

# import typedef NS_ENUM (NSInteger, ZLPersonSex) {ZLPersonSexMale = 0, ZLPersonSexFamale}; @ interface ZLPersonModel: NSObject/** NSString name * / @ property (nonatomic, copy) NSString * name;/** NSUInteger Age * / @ property (nonatomic, assign, readonly) NSUInteger age;/** ZLPersonSex gender * / @ property (nonatomic, assign, readonly) ZLPersonSex sex;+ (instancetype) personWithName: (NSString *) name age: (NSUInteger) age sex: (ZLPersonSex) sex;@end

ZLPersonModel.m

# import "ZLPersonModel.h" @ implementation ZLPersonModel- (instancetype) initWithName: (NSString *) name age: (NSUInteger) age sex: (ZLPersonSex) sex {if (self = [super init]) {_ name = name; _ age = age; _ sex = sex;} return self;} + (instancetype) personWithName: (NSString *) name age: (NSUInteger) age sex: (ZLPersonSex) sex {return [[self alloc] initWithName:name age:age sex:sex] }-(NSString *) description {return [NSString stringWithFormat:@ "[name =% @, age =% ld, sex =% ld]", self.name, self.age, self.sex];} @ end

Let's get down to business.

Example 1: (the simplest use)

ZLPersonModel * sunnyzl = [ZLPersonModel personWithName:@ "sunnyzl" age:29 sex:ZLPersonSexMale]; ZLPersonModel * jack = [ZLPersonModel personWithName:@ "jack" age:22 sex:ZLPersonSexMale]; / / first let's look at some simple uses / / 1. Determine whether the name begins with s NSPredicate * pred1 = [NSPredicate predicateWithFormat:@ "name LIKE's names']; / / output: sunnyzl:1, jack:0 NSLog (@" sunnyzl:%d, jack:%d ", [pred1 evaluateWithObject:sunnyzl], [pred1 evaluateWithObject:jack]); / / 2. Determine whether the age is greater than 25 NSPredicate * pred2 = [NSPredicate predicateWithFormat:@ "age > 25"]; / / output: whether the age of sunnyzl is greater than 25:1, whether the age of jack is greater than 25:0 NSLog (@ "whether the age of sunnyzl is greater than 25% d, whether the age of jack is greater than 25 pred2 evaluateWithObject:jack% d", [pred2 evaluateWithObject:sunnyzl], [pred2 evaluateWithObject:jack])

When we see here, we will find that the evaluateWithObject: method returns a Bool value, YES if the condition is met, and NO if it does not match. And even the simplest use has some great use, for example, we used to write to judge mobile phone numbers, zip codes, and so on, for example, I like to use John Engelhart's RegexKitLite, but because we need to import the libicucore.dylib library (xcode7 is libicucore.tbd) and because mrc needs to add-fno-objc-arc, we can only use it. However, using predicates allows us to achieve the same function with the same concise code.

Example 2:

(judge whether the mobile phone number is correct)

-(BOOL) checkPhoneNumber: (NSString *) phoneNumber {NSString * regex = @ "^ [1] [3-8]\\ d {9} $"; NSPredicate * pred = [NSPredicate predicateWithFormat:@ "SELF MATCHES% @", regex]; return [pred evaluateWithObject:phoneNumber];}

Example 3: detect whether there are special characters in the string

-(BOOL) checkSpecialCharacter: (NSString *) string {NSString * regex = @ "[`~! @ # $^ & * () = | {}':;',\ [\\]. /? ~! @ # ¥. & * ()-- | {} []';:"',?] + "; NSPredicate * pred = [NSPredicate predicateWithFormat:@" SELF MATCHES% @ ", regex]; return [pred evaluateWithObject:string];

two。 Filter collections using predicates

This part is the key point that we need to master, because from here we can see the real power of predicates.

In fact, the predicate itself represents a logical condition, and the result returned after calculating the predicate is always a value of type BOOL. The most common function of predicates is to filter collections. When a program filters a collection element with a predicate, the program automatically traverses its element and calculates the value of the predicate based on the collection element, which is retained when the element in the collection evaluates the predicate and returns YES. Note that the program automatically iterates through its elements, and it reassembles the values returned as YES into a collection.

In fact, it is similar to the next piece of code we used when we set the index with tableView.

-(NSArray *) sectionIndexTitlesForTableView: (UITableView *) tableView {return [self.cityGroup valueForKey:@ "title"];}

[self.cityGroup valueForKey:@ "title"] in. Its purpose is to iterate through all the title and form a new array of the resulting values.

NSArray provides the following method to filter the collection using predicates-(NSArray *) filteredArrayUsingPredicate: (NSPredicate *) predicate: filter the NSArray collection using the specified predicate and return a new collection of eligible elements NSMutableArray provides the following method to filter the collection using predicates-(void) filterUsingPredicate: (NSPredicate *) predicate: filter NSMutableArray using the specified predicate NSSet provides a way to filter the collection using predicates-(NSSet *) filteredSetUsingPredicate: (NSPredicate *) predicate NS_AVAILABLE (10: 5, 3: 0): the method NSMutableSet in NSArray provides the following way to filter the collection using predicates-(void) filterUsingPredicate: (NSPredicate *) predicate NS_AVAILABLE (10: 5, 3: 0): works the same as the method in NSMutableArray. As can be seen from the above description, the difference between using predicates to filter an immutable set and a variable set is that when filtering an immutable set, a new set of qualified set elements is returned; when filtering a variable set, there is no return value. Will directly eliminate the collection elements that do not meet the criteria

Let's look at a few examples:

Example 1:

NSMutableArray * arrayM = [@ [@ 20, @ 40, @ 50, @ 30, @ 60, @ 70] mutableCopy]; / / filter values greater than 50 NSPredicate * pred1 = [NSPredicate predicateWithFormat:@ "SELF > 50"]; [arrayM filterUsingPredicate:pred1]; NSLog (@ "arrayM:%@", arrayM) NSArray * array = @ [[ZLPersonModel personWithName:@ "Jack" age:20 sex:ZLPersonSexMale], [ZLPersonModel personWithName:@ "Rose" age:22 sex:ZLPersonSexFamale], [ZLPersonModel personWithName:@ "Jackson" age:30 sex:ZLPersonSexMale], [ZLPersonModel personWithName:@ "Johnson" age:35 sex:ZLPersonSexMale]]; / / request to take out the element NSPredicate * pred2 = [NSPredicate predicateWithFormat:@ "name CONTAINS 'son'"] containing' son']; NSArray * newArray = [array filteredArrayUsingPredicate:pred2]; NSLog (@ "% @", newArray)

Output as

2016-01-07 16 arrayM: (60,70) 2016-01-07 1650 name 09.511 PredicteDemo [13660 name = Jackson, age = 30, sex = 0], "[name = Johnson, age = 35, sex = 0]")

From this example we can see how powerful NSPredicate is, and if we were to implement it in other ways, it would be a lot of if...else. Let's review the above removal of the same elements from the first array from the second array

Example 2:

NSArray * filterArray = @ [@ "ab", @ "abc"]; NSArray * array = @ [@ "a", @ "ab", @ "abc", @ "abcd"]; NSPredicate * predicate = [NSPredicate predicateWithFormat:@ "NOT (SELF IN% @)", filterArray]; NSLog (@ "% @", [array filteredArrayUsingPredicate:predicate])

The output is:

2016-01-07 13 PredicteDemo 1715 43.669 PredicteDemo [6701 136206] (a, abcd)

If we don't use NSPredicate, there must be all kinds of if...else,for loops and so on. It can be seen that the emergence of NSPredicate has saved us a lot of time and energy.

3. Use placeholder parameters in predicates

In all our examples above, predicates are always fixed, but when we deal with variables in reality, we decide that predicates should be variable. Let's take a look at how to change the predicate.

First of all, if we want to use variables in predicate expressions, we need to understand the following two kinds of placeholders

% K: for dynamically passing in attribute names% @: for dynamically setting attribute values

In fact, it is equivalent to variable name and variable value.

In addition, you can use dynamically changed attribute values in predicate expressions, just like environment variables

NSPredicate * pred = [NSPredicate predicateWithFormat:@ "SELF CONTAINS $VALUE"]

In the above expression, at the beginning, the comparison condition of the predicate expression $VALUE can be changed dynamically as the program changes.

Let's use an example to see how these three important placeholders should be used.

Example 1:

NSArray * array = @ [[ZLPersonModel personWithName:@ "Jack" age:20 sex:ZLPersonSexMale], [ZLPersonModel personWithName:@ "Rose" age:22 sex:ZLPersonSexFamale], [ZLPersonModel personWithName:@ "Jackson" age:30 sex:ZLPersonSexMale], [ZLPersonModel personWithName:@ "Johnson" age:35 sex:ZLPersonSexMale]]; / / define a property to store the attribute name, and define a value to store the value NSString * property = @ "name"; NSString * value = @ "Jack" / / the function of this predicate is to take it into a new array if the property attribute in the element contains the value value, where name contains Jack NSPredicate * pred = [NSPredicate predicateWithFormat:@ "% K CONTAINS% @", property, value]; NSArray * newArray = [array filteredArrayUsingPredicate:pred]; NSLog (@ "newArray:%@", newArray) / / create a predicate with the attribute name changed to age, requiring that the age contain the $VALUE string NSPredicate * predTemp = [NSPredicate predicateWithFormat:@ "% K > $VALUE", @ "age"]; / / specify that the value of $VALUE is 25 NSPredicate * pred1 = [predTemp predicateWithSubstitutionVariables:@ {@ "VALUE": @ 25}]; NSArray * newArray1 = [array filteredArrayUsingPredicate:pred1]; NSLog (@ "newArray1:%@", newArray1) / / modify the value of $VALUE to 32 NSPredicate * pred2 = [predTemp predicateWithSubstitutionVariables:@ {@ "VALUE": @ 32}]; NSArray * newArray2 = [array filteredArrayUsingPredicate:pred2]; NSLog (@ "newArray2:%@", newArray2)

Output as

2016-01-07 17 PredicteDemo 28 name 02.062 PredicteDemo [14542 name 309494] newArray: ("[age = Jack, age = 20, sex = 0]", "[name = Jackson, age = 30, sex = 0]") 2016-01-07 1728 purl 2.063 PredicteDemo [14542WR 309494] newArray1: ("[name = Jackson, age = 30, sex = 0]", "[name = Johnson, age = 35]" Sex = 0] ") 2016-01-07 17 newArray2 28 sex 02.063 PredicteDemo [14542 name 309494] newArray2: (" [name = Johnson, age = 35, sex = 0] ")

From the above example, we can mainly see the meaning of% K and $VALUE.

So this is the end of the introduction of NSPredicate.

The above is the basic introduction to the use of the predicate NSPredicate in iOS. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report