NSpredicate 常用方法

    // 谓词的条件查询 > 、< 、==、!=
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"age > 20"];
NSArray *arr1 = [stuArray filteredArrayUsingPredicate:predicate1];
NSLog(@"arr1 = %@",arr1); //使用表达式
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"age > 20 && height > 170"];
NSArray *arr2 = [stuArray filteredArrayUsingPredicate:predicate2];
NSLog(@"arr2 = %@",arr2); // 字符串作为条件要使用单引号‘’,name == 'lisi'
NSPredicate *predicate3 = [NSPredicate predicateWithFormat:@"name == 'lisi'"];
NSArray *arr3 = [stuArray filteredArrayUsingPredicate:predicate3];
NSLog(@"arr3 = %@",arr3); // 使用占位符
NSPredicate *predicate4 = [NSPredicate predicateWithFormat:@"age == %ld",];
NSArray *arr4 = [stuArray filteredArrayUsingPredicate:predicate4];
NSLog(@"arr4 = %@",arr4); // IN {'lisi','wangwu'} 在包含的条件内
NSPredicate *predicate5 = [NSPredicate predicateWithFormat:@"height IN {165,180}"];
NSArray *arr5 = [stuArray filteredArrayUsingPredicate:predicate5];
NSLog(@"arr5 = %@",arr5); //BEGINSWITH 以什么字符串开头
NSPredicate *predicate6 = [NSPredicate predicateWithFormat:@"name BEGINSWITH[c] 'R'"];
NSArray *arr6 = [stuArray filteredArrayUsingPredicate:predicate6];
NSLog(@"arr6 = %@",arr6); // ENDSWITH 以什么字符串结尾
NSPredicate *predicate7 = [NSPredicate predicateWithFormat:@"name ENDSWITH 'e'"];
NSArray *arr7 = [stuArray filteredArrayUsingPredicate:predicate7];
NSLog(@"arr7 = %@",arr7); // CONTAINS 包含某个字符串
NSPredicate *predicate8 = [NSPredicate predicateWithFormat:@"name CONTAINS 'a'"];
NSArray *arr8 = [stuArray filteredArrayUsingPredicate:predicate8];
NSLog(@"arr8 = %@",arr8); /* LIKE: 1、 LIKE '*a*' 包含某个字符串
2、 LIKE 'j*' 以某个字符串开头
3、 LIKE '*e 以某个字符串结尾
4、 LIKE '?a*' 第二个字符串是 a 的
5、 LIKE[c] 'r*' [c] 表示忽略大小写 *: 星号表示任意个字符位,?问号,表示一个字符位,[c] 表示忽略大小写 */ NSPredicate *predicate9 = [NSPredicate predicateWithFormat:@"name LIKE '*a*'"];
NSArray *arr9 = [stuArray filteredArrayUsingPredicate:predicate9];
NSLog(@"arr9 = %@",arr9); NSPredicate *predicate10 = [NSPredicate predicateWithFormat:@"name LIKE[c] 'r*'"];
NSArray *arr10 = [stuArray filteredArrayUsingPredicate:predicate10];
NSLog(@"arr10 = %@",arr10); NSPredicate *predicate11 = [NSPredicate predicateWithFormat:@"name LIKE '*e'"];
NSArray *arr11 = [stuArray filteredArrayUsingPredicate:predicate11];
NSLog(@"arr11 = %@",arr11); NSPredicate *predicate12 = [NSPredicate predicateWithFormat:@"name LIKE '?a*'"];
NSArray *arr12 = [stuArray filteredArrayUsingPredicate:predicate12];
NSLog(@"arr12 = %@",arr12); // NSMutableArray 使用 filterUsingPredicate,不会返回一个新数组,而是直接覆盖原来的可变数组
NSPredicate *predicate13 = [NSPredicate predicateWithFormat:@"name LIKE '?a*'"];
[stuArray filterUsingPredicate:predicate13];
NSLog(@"stuArray = %@",stuArray);

本文GitHub地址https://github.com/zhangkiwi/iOS_SN_NSPredicate

05-04 06:35