1.先创建一个person对象
@interface Person: NSObject{
NSString *firstNames;
NSString *lastNames;
int age;
}
NSArray *firstNames = @[ @"Alice", @"Bob", @"Charlie",@"Zhai", @"Quentin" ];
NSArray *lastNames = @[ @"Smith", @"Jones", @"Smith",@"Alan", @"Alberts" ];
NSArray *ages = @[@24, @27,@33,@24, @31 ];
NSMutableArray *people = [NSMutableArray array];
[firstNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
People *person = [[People alloc] init];
person.firstName = [firstNames objectAtIndex:idx];
person.lastName = [lastNames objectAtIndex:idx];
person.age = [ages objectAtIndex:idx];
[people addObject:person];
}];
使用方法主要就这几步,以下讲一些常用的NSpredicate的条件
1.逻辑运算符号 > , < , = , >= , <= 都能使用在这里
运算符还可以跟逻辑运算符一起使用,&& , || ,AND, OR 谓词不区分大小写
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 27"];
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name > 'abc' && age > 27"];
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name > 'abc' OR age > 27"];
2.IN
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN {'abc' , 'def' , '123'}"];
3.以xx开头 --beginswith
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH 'N'"];
4.包含 -- contains
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS 'A'"];
模糊搜索的时候可以多个属性条件进行搜索可用
NSPredicate *result = [NSPredicate predicateWithFormat:@"firstName CONTAINS[cd] %@",@“a”];//条件1
NSPredicate *result1 = [NSPredicate predicateWithFormat:@"lastName CONTAINS[cd] %@",@"a"];//条件2
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[result, result1]];//将2个条件整合为1个条件进行搜索,这个为或的关系
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[result, result1]];//将2个条件整合为1个条件进行搜索,这个为and的关系
5.模糊查询--like
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE '*N*'"];
6.以上说的都是对象种的属性匹配,如果数组种都是字符串如何匹配--self
- NSArray *array=[NSArray arrayWithObjects: @"abc", @"def", @"ghi",@"jkl", nil nil];
- NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF=='abc'"];
- NSArray *array2 = [array filteredArrayUsingPredicate:pre];
7.正则表达式
- 正则表达式:
- NSPredicate 使用MATCHES 匹配正则表达式,正则表达式的写法采用international components
- for Unicode (ICU)的正则语法。
- 例:
- NSString *regex = @"^A.+e$";
- NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
- if([pre evaluateWithObject: @"Apple"]){
- printf("YES\n");
- }else{
- printf("NO\n");
- }