技术博客http://www.cnblogs.com/ChenYilong/
新浪微博http://weibo.com/luohanchenyilong
NSPredicate
技术博客http://www.cnblogs.com/ChenYilong/新浪微博http://weibo.com/luohanchenyilong
NSPredicate–谓词(is)
• 作用:判断条件表达式的求值返回真或假的过程
• 使用步骤:- 1. 定义NSPredicate对象并指定条件-2. 调用谓词的evaluateWithObject方法判断指定条件是否满足
• 示例:NSPredicate *predicate = [NSPredicatepredicateWithFormat:@”self
CONTAINS ‘1’”];
NSString *text = @”1234″;
NSLog(@”%d”, [predicate evaluateWithObject:text]);
谓词示例(1)—传统方法
• 1. 创建Person的对象数组
• 2. 编写常规的查询判断姓名和年龄的过滤方法NSMutableArray *result = [NSMutableArrayarrayWithCapacity:personList.count];
for (NSInteger i = 0; i < personList.count; i++) { Person*person = personList[i];
// 用户年龄小于5 同时用户姓名中包含“1”字符串 if(person.age < 5 && NSNotFound != [person.namerangeOfString:@”1″].location) {
[result addObject:person]; }
}
return result;
谓词示例(2)—谓词方法 NSPredicate*predicate = [NSPredicatepredicateWithFormat:@”name
CONTAINS ‘1’ && %K BETWEEN {%d, %d}”,@”age”, 5, 15];
NSArray *result = [personListfilteredArrayUsingPredicate:predicate];
谓词的条件指令(1)—逻辑指令
• &&!
• ||!
• !!
• <!
• <=!
• ==!
• >!
• >=!
• BETWEEN {}!
谓词的条件指令(2)—字符串匹配
• BEGANWITH:以指定字符开始• ENDSWITH:以指定字符结束• CONTAINS:包含指定字符,可使用修饰符
– c 不区分大小写
– d 不区分注音符号 • LIKE:使用通配符匹配
– ? 一个字符- * 0个或多个字符
提示
• 1.谓词中的匹配指令关键字通常使用大写字母• 2.谓词中可以使用格式字符串• 3.如果通过对象的keypath指定匹配条件,需要使用%K
Thanks!
技术博客http://www.cnblogs.com/ChenYilong/
新浪微博http://weibo.com/luohanchenyilong