去苹果的的技术官网搜索-Predicate就会找到相关的文档-Predicate Programming Guide
1,创建谓词时
%@是变量时不加单双引号,常量是加单引号,加双引号需要转义符号
NSPredicate *predicate = [NSPredicate
|
predicateWithFormat:@"(lastName like[cd] %@) AND (birthday > %@)",
|
lastNameSearchString, birthdaySearchDate]; |
2,%K 代表数组键值。
3,看下面例子。
NSMutableArray *array =
|
[NSMutableArray arrayWithObjects:@"Nick", @"Ben", @"Adam", @"Melissa", nil];
|
|
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'a'"];
|
NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate];
|
// beginWithB contains { @"Adam" }.
|
|
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'e'"];
|
[array filterUsingPredicate:sPredicate];
|
// array now contains { @"Nick", @"Ben", @"Melissa" }
|
第一个beginswith[c] 以某个字符开头的,以a开头的,所以只会搜索到 adam。大家仔细看这行代码:NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate];
它会把结果付给beginWithB。array的值不变。
第二个contains[c] 包含某个字符,包含e的,所以会搜索到@"Ben", @“Melissa”(文档里把@"Nick”,放那是错误的。)
看代码:[array filterUsingPredicate:sPredicate];这行代码无返回值,此时array的值变成( Ben,Melissa)。
4,
NSString *firstName = @"Ben";
NSArray *array = @[ @{ @"firstName" : @"Turner" },
@{@"firstName" : @"Ben", @"lastName" : @"Ballard",
@"birthday": [NSDatedateWithString:@"1972-03-24 10:45:32 +0600"] },
@{ @"firstName" : @"Ben" },];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName like %@", firstName];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"filteredArray: %@", filteredArray);
搜索到键fitstName对应的值为Ben的数组。