NSPredicate 谓词条件过滤器

NSPredicate类用于定义用来约束,是对一个或取为内存过滤搜索逻辑条件。

可以使用谓词来表示逻辑条件,用来描述持久性存储和内存中的对象筛选对象。虽然是很常见的NSComparisonPredicate , NSCompoundPredicate和NSExpression的实例创建谓词,你经常创建是通过在NSPredicate类的方法解析的格式字符串谓词。

谓词格式字符串的例子包括:

grade == "7" or firstName like "Shaffiq"

name contains[cd] "itroen"

 (firstName like "Mark") OR (lastName like "Adderley")

 

包含的方法:

+ (NSPredicate *)predicateWithFormat:(NSString *)format.

 

使用示例:

NSString *attributeName = @"firstName";
NSString *attributeValue = @"Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@",attributeName, attributeValue];

 

format 参数说明:

%@ is a var arg substitution for an object value—often a string, number, or date.
%K is a var arg substitution for a key path.

比较符号例表:

Basic Comparisons
=, ==
The left-hand expression is equal to the right-hand expression.
>=, =>
The left-hand expression is greater than or equal to the right-hand expression.
<=, =<
The left-hand expression is less than or equal to the right-hand expression.
>
The left-hand expression is greater than the right-hand expression.
<
The left-hand expression is less than the right-hand expression.
!=, <>
The left-hand expression is not equal to the right-hand expression.

 

字符串比较符

String Comparisons

BEGINSWITH
The left-hand expression begins with the right-hand expression.


CONTAINS
The left-hand expression contains the right-hand expression.


ENDSWITH
The left-hand expression ends with the right-hand expression.


LIKE
The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.


MATCHES
The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).

 

ANY, SOME
Specifies any of the elements in the following expression. For example ANY children.age < 18.


ALL
Specifies all of the elements in the following expression. For example ALL children.age < 18.


NONE
Specifies none of the elements in the following expression. For example, NONE children.age < 18. This is logically equivalent to NOT (ANY ...).


IN
Equivalent to an SQL IN operation, the left-hand side must appear in the collection specified by the right-hand side.
For example, name IN { 'Ben', 'Melissa', 'Nick' }. The collection may be an array, a set, or a dictionary—in the case of a dictionary, its values are used.
In Objective-C, you could create a IN predicate as shown in the following example:
NSPredicate *inPredicate =
            [NSPredicate predicateWithFormat: @"attribute IN %@", aCollection];
where aCollection may be an instance of NSArray, NSSet, NSDictionary, or of any of the corresponding mutable classes.

 

在两者之间

[BETWEEN]

示例:

NSPredicate *betweenPredicate =
    [NSPredicate predicateWithFormat: @"attributeName BETWEEN %@", @[@1, @10]];
 
NSDictionary *dictionary = @{ @"attributeName" : @5 };
 
BOOL between = [betweenPredicate evaluateWithObject:dictionary];
if (between) {
    NSLog(@"between");
}

----------------------------------------------

主要使用的一些关键字例表如下:

 

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

 

实际应用:

(1)对NSArray进行过滤

1 NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];    
2 NSString *string = @"ang";    
3 NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",string];    
4 NSLog(@"%@",[array filteredArrayUsingPredicate:pred]); 

类似如下:

 1 @interface NSMutableArray (NSPredicateSupport)
 2 - (void)filterUsingPredicate:(NSPredicate *)predicate;    // evaluate a predicate against an array of objects and filter the mutable array directly
 3 @end
 4 
 5 
 6 @interface NSSet (NSPredicateSupport)
 7 - (NSSet *)filteredSetUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0);    // evaluate a predicate against a set of objects and return a filtered set
 8 @end
 9 
10 @interface NSMutableSet (NSPredicateSupport)
11 - (void)filterUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0);    // evaluate a predicate against a set of objects and filter the mutable set directly
12 @end
13 
14 @interface NSOrderedSet (NSPredicateSupport)
15 
16 - (NSOrderedSet *)filteredOrderedSetUsingPredicate:(NSPredicate *)p NS_AVAILABLE(10_7, 5_0);    // evaluate a predicate against an ordered set of objects and return a filtered ordered set
17 
18 @end
19 
20 @interface NSMutableOrderedSet (NSPredicateSupport)
21 
22 - (void)filterUsingPredicate:(NSPredicate *)p NS_AVAILABLE(10_7, 5_0);  // evaluate a predicate against an ordered set of objects and filter the mutable ordered set directly
23 
24 @end

 

(2)判断字符串首字母是否为字母:

NSString *regex = @"[A-Za-z]+";  
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];  
  
if ([predicate evaluateWithObject:aString]) {  
}  

(3)字符串替换:

NSError* error = NULL;  
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(encoding=\")[^\"]+(\")"  
                                                                            options:0  
                                                                            error:&error];  
NSString* sample = @"<xml encoding=\"abc\"></xml><xml encoding=\"def\"></xml><xml encoding=\"ttt\"></xml>";  
NSLog(@"Start:%@",sample);  
NSString* result = [regex stringByReplacingMatchesInString:sample  
                                                      options:0  
                                                       range:NSMakeRange(0, sample.length)  
                                                      withTemplate:@"$1utf-8$2"];  
NSLog(@"Result:%@", result);  

 

(4)截取字符串如下:

//组装一个字符串,需要把里面的网址解析出来  
NSString *urlString=@"<meta/><link/><title>1Q84 BOOK1</title></head><body>";  
  
//NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个    
NSError *error;  
  
//http+:[^\\s]* 这个表达式是检测一个网址的。(?<=title\>).*(?=</title)截取html文章中的<title></title>中内文字的正则表达式  
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=title\\>).*(?=</title)" options:0 error:&error];  
  
if (regex != nil) {  
    NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];  
      
    if (firstMatch) {  
        NSRange resultRange = [firstMatch rangeAtIndex:0];  
          
        //从urlString当中截取数据  
        NSString *result=[urlString substringWithRange:resultRange];  
        //输出结果  
        NSLog(@"->%@<-",result);  
    }  
      
}  

(5)判断手机号码,电话号码函数

// 正则判断手机号码地址格式
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
       /**
        * 手机号码
        * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
        * 联通:130,131,132,152,155,156,185,186
        * 电信:133,1349,153,180,189
        */
       NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
       /**
        10         * 中国移动:China Mobile
        11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
        12         */
       NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
       /**
        15         * 中国联通:China Unicom
        16         * 130,131,132,152,155,156,185,186
        17         */
       NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
       /**
        20         * 中国电信:China Telecom
        21         * 133,1349,153,180,189
        22         */
       NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
       /**
        25         * 大陆地区固话及小灵通
        26         * 区号:010,020,021,022,023,024,025,027,028,029
        27         * 号码:七位或八位
        28         */
      // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
     NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
     NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
     NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
     NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
    || ([regextestcm evaluateWithObject:mobileNum] == YES)
    || ([regextestct evaluateWithObject:mobileNum] == YES)
    || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        if([regextestcm evaluateWithObject:mobileNum] == YES) {
          NSLog(@"China Mobile");
        } else if([regextestct evaluateWithObject:mobileNum] == YES) {
          NSLog(@"China Telecom");
        } else if ([regextestcu evaluateWithObject:mobileNum] == YES) {
          NSLog(@"China Unicom");
        } else {
          NSLog(@"Unknow");
        }
        
        return YES;
    }
    else 
    {
        return NO;
    }
}

 

posted @ 2015-11-04 11:30  chensheng12330  阅读(1287)  评论(0编辑  收藏  举报