NSPredicate用于定义一个逻辑条件,通过该条件可以执行搜索或内存中的过滤操作。
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建谓词,要求name以s开头
NSPredicate *pred = [NSPredicate predicateWithFormat: @"name like 's*'"];
FKuser1 = [[FKUser alloc] initWithName:@"sun"pass:@"123"];
//对user1对象使用谓词执行判断
BOOL result1 = [pred evaluateWithObject:user1];//计算谓词的返回结果,为BOOL类型
NSLog(@"user1 的name是否以s开头:%d", result1);
FKUser* user2 = [[FKUser alloc] initWithName:@"bai" pass: @"563"];
//对user1对象使用谓词执行判断
BOOL result2 = [pred evaluteWithObject:user2];
NSLog(@"user2 的name是否以s开头:%d", result2);
}
return 0;
}
如果需要在谓词表达式中使用变量,可以考虑在谓词表达式中使用占位符参数。以下两个占位符参数:
%K:该占位符用于动态传入属性名。
%@:该占位符用于动态设置属性值。
#import <Foundation/Foundation.h>
# import "FKUser.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSSet *set = [NSSet setWithObjects: [[FKuser alloc] initWithName: @"孙悟空" pass: @"343"], [[FKuser alloc] initWithName: @"金角大王" pass: @"231"], [[FKUser alloc] initWithName: @"猪八戒" pass: @"659"],nil];
NSString *proPath = @"name";
NSString *value = @"大王";
//创建谓词,该谓词包含了两个占位符
//后面的两个变量用于为占位符设置参数值
NSPredicate *pred = [NSPredicate predicateWithFormat: @"%K CONTAINS %@", proPath , value];//相当于name CONTAIN 大王
//执行过滤后
NSSet *newSet = [set filteredSetUsingPredicate: pred];
NSLog(@"%@", newSet);
//创建谓词,该谓词表达式中使用%@K占位符,该占位符使用pass代替
//要求被比较的对象的pass包含$SUBSTR子串。 SUBSTR相当于一个变量
NSPredicate *predTemplate = [NSPredicate predicateWithFormat: @"%K CONTAINS $SUBSTR", @"pass"];
//使用NSDictionary 指定SUBSTR的值为‘43’
NSPredicate *pred1 = [predTemplate predicateWithSubstitutionVariables: [NSDictionary dictionaryWithObjectsAndKeys:@"43", @"SUBSTR", nil]];
//执行过滤,过滤后的集合只剩下两个元素
NSSet *newSet1 = [set filteredSetUsingPredicate:pred1];
NSLog(@"%@", newSet1 );
//使用NSDictionary指定SUBSTR的值为‘59’
NSPredicate *pred2 = [predTemplate predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObjectsAndKeys: @"59", @"SUBSTR", nil]];
//执行过滤
NSSet *newSet2 = [set filteredSetUsingPredicate: pred2];
NSLog(@"%@", newSet2);
}
return 0;
}