- 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.jb51.cc/regex/359919.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。