iOS verbs (nspredicate) (regular expressions and Uibarcontroller)

Source: Internet
Author: User

iOS nspredicate (regular expressions and Uibarcontroller)

This article forwards to: 1190000000623005

NSPredicate, this class is as powerful as the valueforkeypath I mentioned in my last blog post. Its use is mainly concentrated in two methods

Nsarray
- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate;
Nsmutablearray
- (void)filterUsingPredicate:(NSPredicate *)predicate;

There are also NSSet and NSMutableSet can be filtered with this class.

I would like to introduce the use of this class, I believe you will see after reading and I think this class is really strong.

Filter usage
    • Using Member instance methods
      Filter out strings that are longer than 3
    NSArray *array = @[@"jim", @"cook", @"jobs", @"sdevm"]; NSPredicate *pre = [NSPredicate predicateWithFormat:@"length > 3"]; NSLog(@"%@", [array filteredArrayUsingPredicate:pre]);

Print

(    cook,    jobs,    sdevm)

lenghtIs that the array member executes [xxxx lenght] and then determines whether the returned Nsuinteger value is greater than 3. Extended to nsstring other methods such asintegerValue

NSArray *array = @[@"2", @"3", @"4", @"5"];NSPredicate *pre = [NSPredicate predicateWithFormat:@"integerValue >= %@", @3];NSLog(@"%@", [array filteredArrayUsingPredicate:pre]);

If I don't want to use any instance method, I want to filter what the member itself should do. You can use it self instead.

NSPredicate *pre = [NSPredicate predicateWithFormat:@"self CONTAINS %@", @3];

CONTAINSThe usage is followed by

Extend to model

Test.h

@interface Test : NSObject@property (nonatomic, strong) NSString *name;@property (nonatomic, strong) NSNumber *code;@end
Test *Test1 = [[Test alloc]init];Test1.name = @ "West Lake"; test1.code = @1; Test *test2 = [[Test alloc]init]; test2.name = @ "Xixi wetland"; test2.code = @2; Test *TEST3 = [[Test alloc]init]; test3.name = @ "Temple of the Temple"; test3.code = @3; Nsarray *array = @[test1, test2, test3]; Nspredicate *pre = [nspredicate predicatewithformat:@ "code >=%@", @2"; NSLog (@ "%@", [array filteredarrayusingpredicate:pre]);      

The filter array member [test code] method (The Get method for the Code property) returns the member of the value >=2. The comparison operators here can also use,,, == != <= < .

In fact, it can be used == not only to compare NSNumber objects, but also to determine whether NSString objects are the same.

NSPredicate *pre = [NSPredicate predicateWithFormat:@"name == %@", @"西湖"];

Filter out an name array of objects that are "West Lake".

    • # # #NSString对象的操作
      As mentioned earlier == , comparison operators can serve as a - (BOOL)isEqualToString:(NSString *)aString; method to determine whether a string is the same. So how does a string contain a string to be judged, and in nspredicate, it can be used CONTAINS (in both case and capitalization) to represent the containing relationship.
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@", @"湖"];

When judging the need to ignore the case can be used[cd]

[C] Ignore case
[d] ignoring accent marks [CD] is neither case sensitive nor pronounced.

Use:

NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", @"abc"];

More complex query statements are involved, such as the use of wildcards to determine whether a string begins or ends with a string.

BEGINSWITH(已某个字符串开头, begins with)
    NSString *targetString = @"h";    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",targetString];
ENDSWITH(已某个字符串结尾, ends with)
    NSString *targetString = @"ing";    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",targetString];
通配符 LIKE
* represents one or more or empty
? Represents a character
Test *Test1 = [[Test alloc]init];Test1.name = @ "ABSR"; test1.code = @1; Test *test2 = [[Test alloc]init]; Test2.name = @ "ASB";  Test2.code = @2; Test *TEST3 = [[Test alloc]init]; Test3.name = @ "raskj";  Test3.code = @3; Nsarray *array = @[test1, test2, test3]; Nspredicate *pre = [nspredicate predicatewithformat:@ "name like%@", @" b* "]; NSLog (@ "%@", [array filteredarrayusingpredicate:pre]);      

The result is that only test1 meet, and like can accept[cd]

NSPredicate *pre = [NSPredicate predicateWithFormat:@"name LIKE[cd] %@", @"?b*"];
Relational operations, including the INBETWEENANDORNOT IN(之中)
NSPredicate *pre = [NSPredicate predicateWithFormat:@"code IN %@", @[@1, @3]];

Determine if code is @1 or @2, that is, whether it is in an array.

OR(或,可以用||代替)

ORcan be used instead to IN achieve the same effect, but OR more flexible.

NSPredicate *pre = [NSPredicate predicateWithFormat:@"code == %@ OR code == %@ ", @1, @3];

Effect and IN the same, but OR can judge more than one property

NSPredicate *pred = [NSPredicate predicateWithFormat:@"code == %@ OR name == %@ ", @1, @"asb"];
BETWEEN(之间)

Typically used to judge NSNumber objects

NSPredicate *pred = [NSPredicate predicateWithFormat:@"code BETWEEN {1, 3}"];

Determine if code is >=1 and <=3

AND(且,可以用&&代替)
NSPredicate *pred = [NSPredicate predicateWithFormat:@"code >= %@ AND code <=%@", @1, @3];
NOT(非,可以用!代替)

NOTThe most common use is to exclude data from an array from another array, which may be a bit around, for example.

    NSArray *arrayFilter = @[@"abc1", @"abc2"];    NSArray *arrayContent = @[@"a1", @"abc1", @"abc4", @"abc2"]; NSPredicate *thePredicate = [NSPredicate predicateWithFormat:@"NOT (SELF in %@)", arrayFilter]; NSLog(@"%@",[arrayContent filteredArrayUsingPredicate:thePredicate]);

Print

(    a1,    abc4)

It is simpler than one or two points to add to the new array compared to the loop comparison.

All of the above mentioned are used + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;Method is created, there is another common method: + (NSPredicate*)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block, created in block form
NSPredicate *pre = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {    Test *test = (Test *)evaluatedObject;    if (test.code.integerValue > 2) { return YES; } else{ return NO; }}];

The parameter evaluatedObject represents the array member, and the block must return yes or no to indicate whether the match or mismatch is true. Please ignore bindings the parameters, I do not understand the specific role.

Multiple filters

If you need to match a number of properties of the filter, with AND or OR to concatenate is obviously a bit cumbersome, the NSCompoundPredicate class can meet our needs, it can be a combination of multiple NSPredicate objects, the combination can be AND either OR .

    Nspredicate *pre1 = [nspredicate predicatewithformat:@  "code >=%@", @3]; nspredicate *pre2 = [nspredicate predicatewithformat:@ "code <=%@", @2]; //and form combination NSPredicate *pre = [ Span class= "hljs-constant" >nscompoundpredicate andpredicatewithsubpredicates:@[pre1, Pre2]]; //or form combination NSPredicate *pre = [ Span class= "hljs-constant" >nscompoundpredicate orpredicatewithsubpredicates:@[pre1, Pre2]];                 
In fact, the nspredicate can be used not only for filtering, but also for judging whether the match is directly returned, the Main method is - (BOOL)evaluateWithObject:(id)object;Usage:
    Test *test1 = [[Test alloc]init];    test1.name = @"absr";    test1.code = @1; NSPredicate *pres = [NSPredicate predicateWithFormat:@"code == %@", @2]; BOOL match = [pres evaluateWithObject:test1];

Of course, the most commonly used is to cooperate with regular expressions, to enumerate a few common regular

Whether to start with a with E end

    NSString *[email protected]"assdbfe";    NSString *[email protected]"^a.+e$";    NSPredicate *pres = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", targetString]; BOOL match = [pres evaluateWithObject:string];

Whether it is a mailbox

NSString *strRegex = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{1,5}"; 

is the phone number

NSString *strRegex = @"[0-9]{1,20}";  
Keng

I have to say that + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...; there is a hole in the Nspredicate object created by the method.

In some cases, strings similar to those in the example above are code not very clear and are used when created

Test *Test1 = [[Test alloc]init];Test1.name = @"ABSR";test1.code = @1; Test *test2 = [[Test alloc]init]; Test2.name = @ "ASB";  Test2.code = @2; Test *TEST3 = [[Test alloc]init]; Test3.name = @ "raskj";  Test3.code = @3; Nsarray *array = @[test1, test2, test3]; Nspredicate *pre = [nspredicate predicatewithformat:@ "%@ = =%@", @  "code", @2]; NSLog (@ "%@", [array filteredarrayusingpredicate:pre]);      

Notice how the Nspredicate object is initialized. Run this code and you will find that the Test2 object is not queried. Print pre discovery "code" == 2 , which shows that finding the "code" return value of a method is obviously not feasible.

If the query is a property, such as code is a property of the test class, then use the following creation method
NSPredicate *pre = [NSPredicate predicateWithFormat:@"%K == %@", @"code", @2];

Will not be the pit

Attention: %KOf KMust be uppercase. At last

Nspredicate can satisfy almost all forms of queries, and database queries with core data are certainly a cinch. Nspredicate usage not only these, interested students can look at the Nshipster site of this blog post, which mentioned some of the usage I did not refer to.

iOS verbs (nspredicate) (regular expressions and Uibarcontroller)

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.