标签:nspredicate 谓词 cocoa coredata
Cocoa 提供了一个名为NSPredicate的类,用于指定过滤器的条件,用NSPredicate描述查询方式,原理类似于在数据库中进行查询。可以在数据库风格的API中使用NSPredicate类,常见的用于Core Data和Spotlight。 本文讲解过程中用到了部分类比如garage(车库的类),car(车)等仅供举例,未列出创建代码,体会predicate的用法才是关键。
创建Predicate.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == 'Herbie'"];
计算Predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"engine.horsepowe > 150"]; NSArray *cars = [garage cars]; for (Car *car in [garage cars]) { if ([predicate evaluateWithObject:car]) { NSLog(@"%@",car.name); } }
数组过滤器
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"engine.horsepowe > 150"]; NSArray *results; results = [cars filteredArrayUsingPredicate:predicate];
NSMutableArray *carsCopy = [cars mutableCopy]; [carsCopy filterUsingPredicate:predicate];
构造灵活Predicate
有两种方式,
第一种 格式说明符
NSPredicate *predicate1, *predicate2, *predicate3; predicate1 = [NSPredicate predicateWithFormat:@"engine.horsepowe > %d",50]; predicate2 = [NSPredicate predicateWithFormat:@"name == %@",@"Herbie"]; predicate3 = [NSPredicate predicateWithFormat:@"%k == %@", @"name", @"Herbie"];
NSPredicate *predicateTemplate = [NSPredicate predicateWithFormat:@"name == $NAME"]; NSDictionary *varDict; varDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Herbie",@"NAME", nil]; NSPredicate *predicate = [predicateTemplate predicateWithSubstitutionVariables:varDict];
predicateTemplate = [NSPredicate predicateWithFormat:@"engine.horsepower > $POWER"]; varDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:150], @"POWER", nil]; predicate = [predicateTemplate predicateWithSubstitutionVariables:varDict];
predicate的运算符
支持C语言的常用运算符 == = > < >= <= != <> && || ! AND OR NOT等
predicate = [NSPredicate predicateWithFormat:@"(engine.horsepower > 50) AND (engine.horsepower < 200)"]; results = [cars filteredArrayUsingPredicate:predicate];
predicate = [NSPredicate predicateWithFormat:@"engine.horsepower BETWEEN{50,200}"];
等价于
NSArray *betweens = [NSArray arrayWithObjects:[NSNumber numberWithInt:50],[NSNumber numberWithInt:200],nil]; predicate = [NSPredicate predicateWithFormat:@"engine.horsepower BEWEEN %@",betweens];
predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", names1]; results = [names2 filteredArrayUsingPredicate:predicate]; NSLog(@"%@", results);答案是:
(
Judge,
Badger
)
字符串运算符
BEGINSWITH 检查某个字符串是否以另一个字符串开头
ENDSWITH 检查某个字符串是否以另一个字符串结尾
转载请注明原著:http://blog.csdn.net/marvindev
标签:nspredicate 谓词 cocoa coredata
原文地址:http://blog.csdn.net/marvindev/article/details/41549459