- 谓词定义
以一个谓词字符串参数来创建NSPredicate对象,如
group.name like “work*”
ALL children.age >12
ANY children.age >12
NSPredicate* pred = [NSPredicate predicateWithFormat:
@"name like 's*'];
User user = [[User alloc] initWithName:@"sun" pass:@"123"];
//name 是否以s开头
BOOL result = [pred evaluateWithObject: user];
谓词支持的语法列表:
比较运算符
逻辑运算符 eg AND,&&,NOT,!
字符串比较运算符 eg. BEGINSWITH,LIKE,MATCHES(后跟正则表达式,效率低)
操作集合的运算符
ANY,SOME :指定只要集合中存在满足条件,即返回YES
ALL,NONE
IN :name IN {‘Ben’,’Nick’}
array[index],array[FIRST],array[SIZE]
2.过滤集合
不可变集合过滤之后会生成新集合并返回,可变集合没有返回值,在原直接剔除了。
-(NSArray )filteredArrayUsingPredicate:(NSPredicate )predicate:
-(NSSet )filteredSetUsingPredicate:(NSPredicate )predicate:
NSMutableArray,NSMutableSet使用:
- (void)filterUsingPredicate:(NSPredicate *)predicate:
NSMutableArray* array = [NSMutableArray arrayWithObjects:
[NSNumber numberWithInt:50],[NSNumber numberWithInt:49],[NSNumber numberWithInt:88],[NSNumber numberWithInt:42],
nil];
// 对象自身大于50
NSPredicate* pred = [NSPredicate predicateWithFormat:
@"SELF > 50"];
[array filterUsingPredicate: pred];
NSSet* set = [NSSet setWithObjects:
[[User alloc] initWithName:@"张三" pass:@"123"],[[User alloc] initWithName:@"李四" pass:@"123"],[[User alloc] initWithName:@"王三" pass:@"123"],[[User alloc] initWithName:@"赵五" pass:@"123"],
nil];
NSPredicate* pred = [NSPredicate predicateWithFormat:
@"name CONTAINS '三'"];
NSSet* newSet = [set filteredSetUsingPredicate: pred];
3.占位符:
%K 动态传入属性名,%@ 动态设置属性值,$SUBSTR 动态改变属性值,类似环境变量
//1
NSString* propPath = @"name";
NSString* value= @"三";
NSPredicate* pred1 = [NSPredicate predicateWithFormat: @"%K CONTAINS %@" ,propPath,value];
//2
NSPredicate* pred2 = [NSPredicate predicateWithFormat: @"%K CONTAINS $SUBSTR" ,@"pass"];
//使用NSDictionary 指定SUBSTR的值是43
NSPredicate* pred2 = [NSPredicate predicateWithSubsititutionVariables:[NSDictionary dictionaryWithObjectAndKeys:@"43",@"SUBSTR",nil]];