定义谓语

谓语用NSPredicate对象来代表三个子类:

NSCompoundPredicate  NSCompoundPredicate和NSExpression

//FKUser是一个自定义的类,包含Name和pass两个属性

NSPredicate* pred=[NSPredicate predicateWithFormat:

@"name like 's*'"];

FKUser* user1=[[FKUser alloc]initWithName:@"sum" pass:@"123"];

BOOL reslult1=[pred evaluateWithObject:

user1];

NSLog(@"user1的name是否以s开头:%d",reslult1);

FKUser* user2=[[FKUser alloc]initWithName:@"bai" pass:@"321"];

BOOL result2=[pred evaluateWithObject:user2];

NSLog(@"user2的name是否以s开头:%d",result2);

NSMutableArray* arr2=[[NSMutableArray alloc] initWithObjects:

@2,@20,@40,@30,@15, nil];

NSPredicate* pred1=[NSPredicate predicateWithFormat:@"self>20"];

[arr2 filterUsingPredicate:

pred1];

NSLog(@"%@",arr2);

NSSet* set=[NSSet setWithObjects:

[[FKUser alloc] initWithName:@"孙悟空" pass:@"123"],

[[FKUser alloc]initWithName:

@"金角大王"pass:@"321"],nil];

NSPredicate* pred2=[NSPredicate predicateWithFormat:

@"name CONTAINS '大王'"];

NSSet* newSet=[set filteredSetUsingPredicate:

pred2];

NSLog(@"%@",newSet);

7.9.3 在谓语中使用占位符参数

1.%K 动态传入属性名

2、%@ 动态设置属性名

如果使用了形如¥SUBSTR的占位符,传入参数:

1、县调用NSPredicate的predicateWithSubstitutionVariables:方法为占位符参数设置参数值,该方法返回一个可用的NSPredicate对象

2.直接调用NSPredicate的evaluateWithObject:substitutionVariables:方法同时完成参数设置和计算结果

NSPredicate* predTemplate=[NSPredicate predicateWithFormat:@"%K contains $SUBSTR",@"pass"];

NSPredicate* pred4=[predTemplate predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObjectsAndKeys:@"123",@"SUBSTR", nil]];

NSSet* newSet3=[set filteredSetUsingPredicate:pred4];

NSLog(@"%@",newSet3);

你可能感兴趣的:(定义谓语)