In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "what is the use of NSPredicate predicates in iOS". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
One NSPredicate understanding explanation
NSPredicate: Chinese literal translation predicate, used to define logical conditional constraint search or in-memory filtering.
Just like the predicate in grammar, such as "greater than" in [3 > 2] is a predicate. To put it simply, it is a logical judgment, like a filter to filter what you need. NSPredicate and [for...] [if..else] function have something in common, simply compare the running efficiency on the mobile phone, the author has consulted [du Niang] [Google], simply said it will improve efficiency, but did not find specific data to explain, the author will not quote. According to the author's personal understanding, NSPredicate is like a chauffeured car service, getting off at the destination; [for...] [if..else] is a bus service, and you can decide which station to get off at. Therefore, NSPredicate has certain convenience, and [for...] [if..else] has wider applicability.
II. NSPredicate syntax description
/ / generally initialize NSPredicate * pred = [NSPredicate predicateWithFormat:@ "...",...]; / / filter with specific objects and return a Bool value [pred evaluateWithObject:...]
Give an example
/ / SELF supports lowercase, representing the object being judged NSNumber * num = @ 999; NSPredicate * pred = [NSPredicate predicateWithFormat:@ "SELF = 999"]; if ([pred evaluateWithObject:num]) {NSLog (@ "% @", num);}
/ / result print 999
It is rarely used this way, because it is not as convenient as [if..else], so let's talk about the usage of NSPredicate.
-0. Collection type method description
NSArray provides:-(NSArray *) filteredArrayUsingPredicate: (NSPredicate *) predicate
NSMutableArray provides:-(void) filterUsingPredicate: (NSPredicate *) predicate
NSSet provides:-(NSSet *) filteredSetUsingPredicate: (NSPredicate *) predicate
NSMutableSet provides:-(void) filterUsingPredicate: (NSPredicate *) predicate
-1. Comparison operator (illustrated by an array)
First encapsulate and create a Person class (there should be no code)
/ / create an array of Person classes Person * p0 = [Person personName:@ "ZhangSan" withAge:20 withSex:@ "man"]; Person * p1 = [Person personName:@ "HanMeiMei" withAge:12 withSex:@ "woman"]; Person * p2 = [Person personName:@ "LiLei" withAge:13 withSex:@ "man"]; Person * p3 = [Person personName:@ "XiaoHua" withAge:13 withSex:@ "woman"]; NSArray * arr = @ [p0, p1, p2, p3]
/ * * comparison operator * / NSPredicate * pred = [NSPredicate predicateWithFormat:@ "age
< %@", @20]; NSArray *resultArr = [arr filteredArrayUsingPredicate:pred]; NSLog(@"年龄小于20 :%@", resultArr); pred = [NSPredicate predicateWithFormat:@"sex = 'woman' && age = 13"]; resultArr = [arr filteredArrayUsingPredicate:pred]; NSLog(@"年龄为13的女性 : %@", resultArr); NSMutableArray *arrayM = [@[@20, @40, @50, @30, @60, @70] mutableCopy];// 可以用 'BETWEEN {30, 50}' 代替 '>'/ / pred = [NSPredicate predicateWithFormat:@ "SELF > 50"]; pred = [NSPredicate predicateWithFormat:@ "SELF BETWEEN {30,50}"]; [arrayM filterUsingPredicate:pred]; NSLog (@ "variable array filtering:% @", arrayM)
/ / print the result
Under the age of 20
"HanMeiMei, 12, woman", "LiLei, 13, man", "XiaoHua, 13, woman")
Women at the age of 13
"XiaoHua, 13, woman")
Variable array filtering: (40,50,30)
-2. String operator
BEGINSWITH: check whether a string begins with a specified string (such as determining whether a string begins with a: BEGINSWITH 'a')
ENDSWITH: check whether a string ends with a specified string
CONTAINS: checks whether a string contains the specified string
LIKE: checks whether a string matches the specified string template. And then you can follow? Two wildcards that represent one character and any number of characters. For example, "name LIKE 'ac'", which means that if the value of name contains ac, it returns YES; "name LIKE'? ac'", which means that YES is returned if the second and third characters of name are ac.
MATCHES: checks whether a string matches the specified regular expression. Although regular expressions are the least efficient in execution, they are the most powerful and most commonly used.
Note: string comparisons are case-sensitive and accented. For example, cafe and cafe are different, and so are Cafe and cafe. If you want string comparison operations to be case-insensitive and accented, use the [c], [d] option after these operators. Where [c] is case-insensitive and [d] is accent-insensitive, which is written after the string comparison operator, for example: name LIKE [cd] 'cafe', then the expression above name will return YES regardless of whether it is cafe, Cafe or caf é.
Give examples to illustrate
/ / create an array of Person classes Person * p0 = [Person personName:@ "ZhangSan" withAge:20 withSex:@ "man"]; Person * p1 = [Person personName:@ "HanMeiMei" withAge:12 withSex:@ "woman"]; Person * p2 = [Person personName:@ "LiLei" withAge:13 withSex:@ "man"]; Person * p3 = [Person personName:@ "XiaoHua" withAge:13 withSex:@ "woman"]; NSArray * arr = @ [p0, p1, p2, p3]
Pred = [NSPredicate predicateWithFormat:@ "name LIKE'? an*'"]; / / the third and fourth digits in the name are an. ResultArr = [arr filteredArrayUsingPredicate:pred]; NSLog (@ "1" ️:% @ ", resultArr); pred = [NSPredicate predicateWithFormat:@" name LIKE'* an*' "]; / / contains the string template an. ResultArr = [arr filteredArrayUsingPredicate:pred]; NSLog (@ "2" ️:% @ ", resultArr); pred = [NSPredicate predicateWithFormat:@" NOT (name CONTAINS 'ua') "]; / / does not include ua. ResultArr = [arr filteredArrayUsingPredicate:pred]; NSLog (@ "3" ️:% @ ", resultArr); pred = [NSPredicate predicateWithFormat:@" name LIKE'* ua*' "]; NSLog (@" judgment returns Bool value:% d ", [pred evaluateWithObject:p3])
/ / print the result
"1 ️: (" ZhangSan, 20, man ")
2 "️: (" ZhangSan, 20, man "," HanMeiMei, 12, woman ")
3 "️: (" ZhangSan, 20, man "," HanMeiMei, 12, woman "," LiLei, 13, man ")
The Bool value returned by judgment is 1.
An example of MATCHES
/ * * predicate matching regular * / NSString * phoneStr = @ "15242335566"; NSLog (@ "Verification:% d", [self checkPhoneNumber:phoneStr])
/ / result print verification: 1
-(BOOL) checkPhoneNumber: (NSString *) phoneNumber {NSString * regex = @ "^ [1] [3-8]\\ d {9} $"; NSPredicate * pred = [NSPredicate predicateWithFormat:@ "SELF MATCHES% @", regex]; return [pred evaluateWithObject:phoneNumber]; / / use predicates only when the regular expression is ^ expression $, not in all cases. Specify, check the reference link at the end of the article, and the author will no longer expand the description}.
-3. Set operator
ANY, SOME: return YES if any element in the collection satisfies the condition.
ALL: YES is returned only if all elements in the collection meet the condition.
NONE: returns YES if no element in the collection satisfies the condition. Such as: NONE person.age
< 18,表示person集合中所有元素的age>The YES is returned at 18:00.
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.
Give an example
/ * * remove the same elements from the first array from the second array * / NSArray * filterArray = @ [@ "ab", @ "abc"]; NSArray * array = @ [@ "a", @ "ab", @ "abc", @ "abcd"]; pred = [NSPredicate predicateWithFormat:@ "NOT (SELF IN% @)", filterArray]; NSLog (@ "remove the same element:% @", [array filteredArrayUsingPredicate:pred])
/ / result printing removes the same elements: (a, abcd)
-4. Use placeholder parameters in predicates
First, if we want to use variables in predicate expressions, we need to understand the following two placeholders:
% K: for dynamically passing in attribute names% @: for dynamically setting attribute values is actually equivalent to variable names and variable values
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, $VALUE is a value that can be changed dynamically. It is actually a key in the dictionary, so you can write different values according to your needs, but it must start with $. As the program changes the comparison condition of the predicate expression $VALUE, it can be changed dynamically.
Give an example
/ / create an array of Person classes Person * p0 = [Person personName:@ "ZhangSan" withAge:20 withSex:@ "man"]; Person * p1 = [Person personName:@ "HanMeiMei" withAge:12 withSex:@ "woman"]; Person * p2 = [Person personName:@ "LiLei" withAge:13 withSex:@ "man"]; Person * p3 = [Person personName:@ "XiaoHua" withAge:13 withSex:@ "woman"]; NSArray * arr = @ [p0, p1, p2, p3]
NSString * property = @ "name"; NSString * value = @ "LiLei"; / / the predicate is used to take it into a new array if the property attribute of the element contains the value value, where name contains LiLei pred = [NSPredicate predicateWithFormat:@ "% K CONTAINS% @", property, value]; NSArray * newArray = [arr 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 $SUBSTR is 12 where the $SUBSTR in the comment is changed to $VALUE NSPredicate * pred1 = [predTemp predicateWithSubstitutionVariables:@ {@ "VALUE": @ 12}]; NSArray * newArray1 = [arr filteredArrayUsingPredicate:pred1]; NSLog (@ "newArray1:%@", newArray1) / / modify the value of $SUBSTR to 13, where the SUBSTR in the comment is changed to $VALUE NSPredicate * pred2 = [predTemp predicateWithSubstitutionVariables:@ {@ "VALUE": @ 13}]; NSArray * newArray2 = [arr filteredArrayUsingPredicate:pred2]; NSLog (@ "newArray2:%@", newArray2)
/ / print the result
NewArray: ("LiLei, 13, man")
NewArray1: ("ZhangSan, 20, man", "LiLei, 13, man", "XiaoHua, 13, woman")
NewArray2: ("ZhangSan, 20, man")
-5. Reserved words in predicates
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
This is the end of the content of "what is the use of NSPredicate predicate in iOS". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.