ios 学习之 NSPredicate 模糊、精确、查询 ,包括模糊搜索,多条件搜索,及属性中多个字段检索

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 谓词不区分大小写
  1. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 27"];  
  2. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name > 'abc' && age > 27"];  
  3. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name > 'abc' OR age > 27"]; 

2.IN

  1. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN {'abc' , 'def' , '123'}"]; 
3.以xx开头 --beginswith 

  1. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH 'N'"];//name以N打头的person 

4.包含 -- contains
         NSPredicate
 *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS 'A'"]; //name种包含'N的person
 

模糊搜索的时候可以多个属性条件进行搜索可用


     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
  1. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE '*N*'"];//*表示零个或多个字符 



6.以上说的都是对象种的属性匹配,如果数组种都是字符串如何匹配--self
  1. NSArray *array=[NSArray arrayWithObjects@"abc"@"def"@"ghi",@"jkl", nil nil];  
  2. NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF=='abc'"];  
  3. NSArray *array2 = [array filteredArrayUsingPredicate:pre]; 

 7.正则表达式

  1. 正则表达式:  
  2. NSPredicate 使用MATCHES 匹配正则表达式,正则表达式的写法采用international components  
  3. for Unicode (ICU)的正则语法。  
  4. 例:  
  5. NSString *regex = @"^A.+e$";//以A 开头,以e 结尾的字符。  
  6. NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];  
  7. if([pre evaluateWithObject@"Apple"]){  
  8. printf("YES\n");  
  9. }else{  
  10. printf("NO\n");  





 

猜你喜欢

转载自blog.csdn.net/ZhaiAlan/article/details/53078771