Cocoa框架中的NSPredicate用于查询,原理和用法类似于SQL中的where,作用相当于数据库的过滤器。
下面是几种常用的方法。
1.比较运算符>,<,==,>=,<=,!=
可用于数值及字符串
NSArray *firstNames = @[ @"张", @"王", @"李", @"李" ];
NSArray *lastNames = @[ @"三", @"五", @"四", @"三" ];
NSArray *ages = @[ @34, @27, @20, @31 ];
NSMutableArray *people = [NSMutableArray array];
[firstNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Person *person = [[Person alloc] init];
person.firstName = firstNames[idx];
person.lastName = lastNames[idx];
person.age = ages[idx];
[people addObject:person];
}];
NSPredicate *liPredicate = [NSPredicate predicateWithFormat:@"firstName = ‘李‘"];
NSPredicate *thirtiesPredicate = [NSPredicate predicateWithFormat:@"age >= 30"];
NSArray *personArray = [people filteredArrayUsingPredicate:liPredicate];
for (Person *people in personArray) {
NSLog(@"李 : %@ ,%@, %@", people.firstName,people.lastName,people.age);
}
NSArray *ageArray = [people filteredArrayUsingPredicate:thirtiesPredicate];
for (Person *people in ageArray) {
NSLog(@"age : %@ ,%@, %@", people.firstName,people.lastName,people.age);
}
Log:
2015-09-22 15:51:57.611 CoreDataDemo[7464:207110] 李 : 李 ,四, 30
2015-09-22 15:51:57.611 CoreDataDemo[7464:207110] 李 : 李 ,三, 31
2015-09-22 15:51:57.612 CoreDataDemo[7464:207110] age : 张 ,三, 34
2015-09-22 15:51:57.612 CoreDataDemo[7464:207110] age : 李 ,三, 31
2.范围运算符:IN、BETWEEN
例:@"number BETWEEN {1,5}"
@"address IN {‘shanghai‘,‘beijing‘}"
IN:
NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];
NSString *string = @"ang";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"%@ in SELF",string];
NSLog(@"%@",[array filteredArrayUsingPredicate:pred]);
Log:
2015-09-22 16:02:51.360 CoreDataDemo[7765:215760] (
shanghai,
guangzou
)
bewteen:
NSPredicate * predicate = [NSPredicate predicateWithFormat:
@"age BETWEEN { 31, 34 }"];
NSArray *results = [people filteredArrayUsingPredicate: predicate];
for (Person *people in results) {
NSLog(@"李 : %@ ,%@, %@", people.firstName,people.lastName,people.age);
}
log:
2015-09-22 16:11:14.634 CoreDataDemo[7984:222771] 李 : 张 ,三, 34
2015-09-22 16:11:14.634 CoreDataDemo[7984:222771] 李 : 李 ,三, 31
3.字符串本身:SELF
例:@“SELF == ‘APPLE’"
4.字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
例:@"name CONTAIN[cd] ‘ang‘" //包含某个字符串
@"name BEGINSWITH[c] ‘sh‘" //以某个字符串开头
@"name ENDSWITH[d] ‘ang‘" //以某个字符串结束
注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。
5.通配符:LIKE
例:@"name LIKE[cd] ‘*er*‘" //*代表通配符,Like也接受[cd].
@"name LIKE[cd] ‘???er*‘"