// // main.m // 谓词 // // Created by MAC on 15/12/21. // Copyright © 2015年 MAC. All rights reserved. // #import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { //谓词 NSPredicate //对集合进行运算 //后面是条件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"age=%d",20]; //Key %k NSPredicate *pre3 = [NSPredicate predicateWithFormat:@"%K=%d",@"age"]; Person *p1 = [[Person alloc]init]; p1.pid = 1; p1.name =@"tom"; p1.age = 20; Person *p2 = [[Person alloc]init]; p2.pid = 2; p2.name =@"kite"; p2.age = 20; Person *p3 = [[Person alloc]init]; p3.pid = 3; p3.name =@"lll"; p3.age = 30; //判断条件 返回值为Bool BOOL b = [pre evaluateWithObject:p2]; NSLog(@"%@",b==1?@"YES":@"NO"); //遍历p1 p2 p3 找出年龄等于20的人 NSArray *array = @[p1,p2,p3]; // NSPredicate *pre1 = [NSPredicate predicateWithFormat:@"age>%d&&age<%d",20,50]; //BETWEEN{20,30}在20到30之间 NSPredicate *pre1 = [NSPredicate predicateWithFormat:@"age BETWEEN {21,50}"]; for (Person *per in array) { BOOL b = [pre1 evaluateWithObject:per]; if(b){ NSLog(@"%@,%d",per.name,per.age); } } //直接过滤数组(重要简单) array = [array filteredArrayUsingPredicate:pre1]; NSLog(@"%@",array); //数组的范围过滤年龄 NSArray *ar = @[[NSNumber numberWithInt:20],[NSNumber numberWithInt:30]]; NSPredicate *pp = [NSPredicate predicateWithFormat:@"age BETWEEN %@",ar]; for (Person *per in array) { BOOL b = [pp evaluateWithObject:per]; if(b){ NSLog(@"%@,%d",per.name,per.age); } } NSArray *aa = @[@"tom1",@"tom2",@"...tom",@"kite",@"kite1",@"xiao he",]; //数组里面的本身就是字符串 用SELF (self) NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF=%@",@"tom"]; // aa = [aa filteredArrayUsingPredicate:predicate]; NSLog(@"%@",aa); //找出以特定开始字符串开头的(beginswith) NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@",@"t"]; // aa = [aa filteredArrayUsingPredicate:predicate1]; NSLog(@"..%@",aa); //找出以特定结尾字符串结尾的(endswith) NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"SELF ENDSWITH %@",@"he"]; // aa = [aa filteredArrayUsingPredicate:predicate2]; NSLog(@"%@",aa); //包含特定字符串的contains NSPredicate *predicate3 = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",@"t"]; // aa = [aa filteredArrayUsingPredicate:predicate3]; NSLog(@"%@",aa); //开头 ?表示后面可以有单个字符 两个??代表两个字符 *代表若干个 NSPredicate *predicate4 = [NSPredicate predicateWithFormat:@"SELF LIKE ‘tom*‘"]; aa = [aa filteredArrayUsingPredicate:predicate4]; NSLog(@"11%@",aa); } return 0; }
时间: 2024-10-10 21:50:21