[iOS学习] 谓词NSPredicate使用

##1. 简单使用
###定义(最常用到的方法):

NSPredicate *ca = [NSPredicate predicateWithFormat:(NSString *), ...];

Format:

  • 比较运算符>,<,==,>=,<=,!=
    可用于数值及字符串
    例:@“number > 100”

  • 范围运算符:IN、BETWEEN
    例:@“number BETWEEN {1,5}”
    @“address IN {‘shanghai’,‘beijing’}”

  • 字符串本身:SELF
    例:@“SELF == ‘APPLE’"

  • 字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
    例:@“name CONTAIN[cd] ‘ang’” // 包含某个字符串
    @“name BEGINSWITH[c] ‘sh’” // 以某个字符串开头
    @“name ENDSWITH[d] ‘ang’” // 以某个字符串结束

  • 通配符:LIKE
    例:@“name LIKE[cd] ‘er’” // 代表通配符,Like也接受[cd].
    @"name LIKE[cd] '???er
    ’"

  • 正则表达式:MATCHES
    例:NSString *regex = @"^A.+e$"; // 以A开头,e结尾
    @“name MATCHES %@”, regex

- (void)testBase {
    Person *jack = [Person personWithName:@"jack" age:56 sex:PersonSexMan];
    Person *sunny = [Person personWithName:@"sunny" age:35 sex:PersonSexMan];
    
    // 1. 判断姓名是否以j开头
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"name LIKE 'j*'"];
    if ([pred1 evaluateWithObject:jack]) {
        NSLog(@"YES, 是以j开头的");
    } else {
        NSLog(@"NO, 不是以j开头的");
    }
    
    // 2. 判断年龄是否大于40
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"age > 40"];
    if ([pred2 evaluateWithObject:sunny]) {
        NSLog(@"YES");
    } else {
        NSLog(@"NO");
    }
}

#pragma mark - 检测特殊字符(存在问题,不能同时检测两个或两个以上特殊字符组成的字符串)
// 可使用NSRegularExpression代替,用NSRegularExpression时会发现匹配到一个结果时就会存入数组,再从匹配到的位置继续向下匹配。然而NSPredicate并不会做这样的自动操作
- (BOOL)checkSpecialCharacter:(NSString *)string {
    NSString *regex = @"^[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:string];
}

#pragma mark - 正则表达式匹配手机号码
- (BOOL)checkPhoneNumber:(NSString *)phoneNumber {
    NSString *regex = @"^[1][3-8]\\d{9}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:phoneNumber];
}

##2. 使用谓词过滤集合

  1. NSArray提供了如下方法使用谓词来过滤集合
  • (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate:使用指定的谓词过滤NSArray集合,返回符合条件的元素组成的新集合
  1. NSMutableArray提供了如下方法使用谓词来过滤集合
  • (void)filterUsingPredicate:(NSPredicate *)predicate:使用指定的谓词过滤NSMutableArray,剔除集合中不符合条件的元素
  1. NSSet提供了如下方法使用谓词来过滤集合
  • (NSSet *)filteredSetUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0):作用同NSArray中的方法
  1. NSMutableSet提供了如下方法使用谓词来过滤集合
  • (void)filterUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0):作用同NSMutableArray中的方法。

总结: 通过上面的描述可以看出,使用谓词过滤不可变集合和可变集合的区别是:过滤不可变集合时,会返回符合条件的集合元素组成的新集合;过滤可变集合时,没有返回值,会直接剔除不符合条件的集合元素

- (void)testArray {
   NSMutableArray *arrayM = [@[@20, @40, @50, @30, @60, @70] mutableCopy];
   //  过滤大于50的值
   NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF > 50"];
   [arrayM filterUsingPredicate:pred1];
   NSLog(@"arrayM:%@", arrayM);
   
   NSArray *array = @[[Person personWithName:@"Jack" age:20 sex:PersonSexMan],
                      [Person personWithName:@"Rose" age:22 sex:PersonSexWoman],
                      [Person personWithName:@"Jackson" age:30 sex:PersonSexMan],
                      [Person personWithName:@"Johnson" age:35 sex:PersonSexMan]];
   //  要求取出包含‘son’的元素
   NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"name CONTAINS 'son'"];
   NSArray *newArray = [array filteredArrayUsingPredicate:pred2];
   NSLog(@"%@", newArray);
}

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

##3. 在谓词中使用占位符参数
%K:用于动态传入属性名
%@:用于动态设置属性值
其实相当于变量名与变量值
除此之外,还可以在谓词表达式中使用动态改变的属性值,就像环境变量一样

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

上述表达式中,$VALUE 是一个可以动态变化的值,它其实最后是在字典中的一个key,所以可以根据你的需要写不同的值,但是必须有$开头,随着程序改变$VALUE这个谓词表达式的比较条件就可以动态改变。

 - (void)testPlaceholder {
    NSArray *array = @[[Person personWithName:@"Jack" age:20 sex:PersonSexMan],
                       [Person personWithName:@"Rose" age:22 sex:PersonSexWoman],
                       [Person personWithName:@"Jackson" age:30 sex:PersonSexMan],
                       [Person personWithName:@"Johnson" age:35 sex:PersonSexMan]];
    //  定义一个property来存放属性名,定义一个value来存放值
    NSString *property = @"name";
    NSString *value = @"Jack";
    //  该谓词的作用是如果元素中property属性含有值value时就取出放入新的数组内,这里是name包含Jack
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K CONTAINS %@", property, value];
    NSArray *newArray = [array filteredArrayUsingPredicate:pred];
    NSLog(@"newArray:%@", newArray);
    
    //  创建谓词,属性名改为age,要求这个age包含$VALUE字符串
    NSPredicate *predTemp = [NSPredicate predicateWithFormat:@"%K > $VALUE", @"age"];
    // SubstitutionVariables替换变量 : 指定$VALUE的值为 25
    NSPredicate *pred1 = [predTemp predicateWithSubstitutionVariables:@{@"VALUE" : @25}];
    NSArray *newArray1 = [array filteredArrayUsingPredicate:pred1];
    NSLog(@"newArray1:%@", newArray1);
    
    //  修改 $VALUE的值为32
    NSPredicate *pred2 = [predTemp predicateWithSubstitutionVariables:@{@"VALUE" : @32}];
    NSArray *newArray2 = [array filteredArrayUsingPredicate:pred2];
    NSLog(@"newArray2:%@", newArray2);
}

相关链接:

  1. ios 学习之 NSPredicate 模糊、精确、查询
  2. iOS中的谓词(NSPredicate)使用
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值