- Cocoa用NSPredicate描述查询的方式,原理类似于在数据库中进行查询
- 计算谓词:
- //基本的查询
- NSPredicate*predicate;
- predicate=[NSPredicatepredicateWithFormat:@"name=='Herbie'"];
- BOOLmatch=[predicateevaluateWithObject:car];
- NSLog(@"%s",(match)?"YES":"NO");
- //在整个cars里面循环比较
- predicate=[NSPredicatepredicateWithFormat:@"engine.horsepower>150"];
- NSArray*cars=[garagecars];
- for(Car*carin[garagecars]){
- if([predicateevaluateWithObject:car]){
- NSLog(@"%@",car.name);
- }
- }
- //输出完整的信息
- predicate=[NSPredicatepredicateWithFormat:@"engine.horsepower>150"];
- NSArray*results;
- results=[carsfilteredArrayUsingPredicate:predicate];
- //含有变量的谓词
- NSPredicate*predicateTemplate=[NSPredicatepredicateWithFormat:@"name==$NAME"];
- NSDictionary*varDict;
- varDict=[NSDictionarydictionaryWithObjectsAndKeys:
- @"Herbie",@"NAME",nil];
- predicate=[predicateTemplatepredicateWithSubstitutionVariables:varDict];
- NSLog(@"SNORGLE:%@",predicate);
- match=[predicateevaluateWithObject:car];
- NSLog(@"%s",(match)?"YES":"NO");
- //注意不能使用$VARIABLE作为路径名,因为它值代表值
- //谓词字符窜还支持c语言中一些常用的运算符
- predicate=[NSPredicatepredicateWithFormat:
- @"(engine.horsepower>50)AND(engine.horsepower<200)"];
- results=[carsfilteredArrayUsingPredicate:predicate];
- NSLog(@"oop%@",results);
- predicate=[NSPredicatepredicateWithFormat:@"name<'Newton'"];
- NSLog(@"%@",[resultsvalueForKey:@"name"]);
- //强大的数组运算符
- @"engine.horsepowerBETWEEN{50,200}"];
- NSArray*betweens=[NSArrayarrayWithObjects:
- [NSNumbernumberWithInt:50],[NSNumbernumberWithInt:200],nil];
- predicate=[NSPredicatepredicateWithFormat:@"engine.horsepowerBETWEEN%@",betweens];
- predicateTemplate=[NSPredicatepredicateWithFormat:@"engine.horsepowerBETWEEN$POWERS"];
- varDict=[NSDictionarydictionaryWithObjectsAndKeys:betweens,@"POWERS",nil];
- predicate=[predicateTemplatepredicateWithSubstitutionVariables:varDict];
- //IN运算符
- predicate=[NSPredicatepredicateWithFormat:@"nameIN{'Herbie','Snugs','Badger','Flap'}"];
- predicate=[NSPredicatepredicateWithFormat:@"SELF.nameIN{'Herbie','Flap'}"];
- "name"]);
- names=[carsvalueForKey:@"name"];
- predicate=[NSPredicatepredicateWithFormat:@"SELFIN{'Herbie',248)"> results=[namesfilteredArrayUsingPredicate:predicate];//这里限制了SELF的范围
- //BEGINSWITH,ENDSWITH,CONTAINS
- //附加符号,[c],[d],[cd],c表示不区分大小写,d表示不区分发音字符,cd表示什么都不区分
- predicate=[NSPredicatepredicateWithFormat:@"nameBEGINSWITH'Bad'"];
- predicate=[NSPredicatepredicateWithFormat:@"nameBEGINSWITH'HERB'"];
- predicate=[NSPredicatepredicateWithFormat:@"nameBEGINSWITH[cd]'HERB'"];
- //LIKE运算符(通配符)
- predicate=[NSPredicatepredicateWithFormat:@"nameLIKE[cd]'*er*'"];
- predicate=[NSPredicatepredicateWithFormat:@"nameLIKE[cd]'???er*'"];
- 原文链接:https://www.f2er.com/regex/359919.html