美文网首页
ios-Predicate介绍

ios-Predicate介绍

作者: 命运建筑师fly | 来源:发表于2017-10-25 08:29 被阅读0次
    /
    /熟悉Predicate
    //[self testPredicateDefinition];
    
    //学习Predicate的比较功能
    //[self testPredicateComparation];
    
    //学习Predicate范围运算功能
    //[self testPredicateRange];
    
    //学习Predicate 与自身相比的功能
    //[self testPredicateComparationToSelf];
    
    //学习Predicate 字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
    //[self testPredicateRelateToNSString];
    
    //学习Predicate 的通配
    [self testPredicateWildcard];
    }
    
    #pragma mark Predicate 的通配
    - (void)testPredicateWildcard{
    /*
    (5)通配符:LIKE
    例:@"name LIKE[cd] '*er*'"
    // *代表通配符,Like也接受[cd].
    @"name LIKE[cd] '???er*'"
    */
    NSArray *placeArray = [NSArray arrayWithObjects:@"Shanghai",@"Hangzhou",@"Beijing",@"Macao",@"Taishan", nil];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like '*ai*' "];
    
    NSArray *tempArray = [placeArray filteredArrayUsingPredicate:predicate];
    [tempArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"obj == %@",obj);
    }];
    
    }
    
    #pragma mark Predicate 字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
    - (void)testPredicateRelateToNSString{
    /*
    (4)字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
    例:@"name CONTAIN[cd] 'ang'" //包含某个字符串
    @"name BEGINSWITH[c] 'sh'" //以某个字符串开头
    @"name ENDSWITH[d] 'ang'" //以某个字符串结束
    注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。
    */
    NSArray *placeArray = [NSArray arrayWithObjects:@"Shanghai",@"Hangzhou",@"Beijing",@"Macao",@"Taishan", nil];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS [cd] 'an' "];
    // NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF Beginswith [cd] 'sh' "];
    
    NSArray *tempArray = [placeArray filteredArrayUsingPredicate:predicate];
    [tempArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"obj == %@",obj);
    }];
    
    }
    
    #pragma mark Predicate 与自身相比的功能
    - (void)testPredicateComparationToSelf{
    /*
    (3)字符串本身:SELF
    例:@“SELF == ‘APPLE’"
    */
    
    NSArray *placeArray = [NSArray arrayWithObjects:@"Shanghai",@"Hangzhou",@"Beijing",@"Macao",@"Taishan", nil];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == 'Beijing'"];
    NSArray *tempArray = [placeArray filteredArrayUsingPredicate:predicate];
    [tempArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"obj == %@",obj);
    }];
    
    }
    
    #pragma mark Predicate范围运算功能
    - (void)testPredicateRange{
    /*
    (2)范围运算符:IN、BETWEEN
    例:@"number BETWEEN {1,5}"
    @"address IN {'shanghai','beijing'}"
    */
    NSArray *array = [NSArray arrayWithObjects:@1,@2,@3,@4,@5,@2,@6, nil];
    //NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF in {2,5}"]; 找到 in 的意思是array中{2,5}的元素
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BETWEEN {2,5}"];
    NSArray *fliterArray = [array filteredArrayUsingPredicate:predicate];
    [fliterArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"fliterArray = %@",obj);
    }];
    
    }
    
    #pragma mark 测试Predicate的比较功能
    - (void)testPredicateComparation{
    /*
    (1)比较运算符>,<,==,>=,<=,!=
    可用于数值及字符串
    例:@"number > 100"
    */
    NSArray *array = [NSArray arrayWithObjects:@1,@2,@3,@4,@5,@2,@6, nil];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF >4"];
    NSArray *fliterArray = [array filteredArrayUsingPredicate:predicate];
    [fliterArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"fliterArray = %@",obj);
    }];
    }
    
    #pragma mark 熟悉Predicate
    - (void)testPredicateDefinition{
    NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];;
    //表示在数组里面筛选还有@"be"的字符串
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",@"be"];
    NSArray *temp = [array filteredArrayUsingPredicate:predicate];
    [temp enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"temp = %@",obj);
    }];
    
    /***************************************************************/
    //NSPredicate给我留下最深印象的是两个数组求交集的一个需求,如果按照一般写法,需要2个遍历,但NSArray提供了一个filterUsingPredicate的方法,用了NSPredicate,就可以不用遍历!
    NSArray *array1 = [NSArray arrayWithObjects:@1,@2,@3,@5,@5,@6,@7, nil];
    NSArray *array2 = [NSArray arrayWithObjects:@4,@5, nil];
    // 表示筛选array1在array2中的元素!YES!其中SELF指向filteredArrayUsingPredicate的调用者。
    /*测试方案:
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF in %@",array2];
    NSArray *temp1 = [array1 filteredArrayUsingPredicate:predicate1];
    结果:
    2015-11-08 10:55:19.879 NSPredicateDemo[11595:166012] obj ==5
    2015-11-08 10:55:19.879 NSPredicateDemo[11595:166012] obj ==5
    
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"SELF in %@",array1];
    NSArray *temp1 = [array2 filteredArrayUsingPredicate:predicate1];
    结果:
    2015-11-08 10:55:19.879 NSPredicateDemo[11595:166012] obj ==5
    
    */
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF in %@",array2];
    NSArray *temp1 = [array1 filteredArrayUsingPredicate:predicate1];
    
    [temp1 enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"temp1 = %@",obj);
    }];
    
    /*
    2015-11-08 10:55:19.879 NSPredicateDemo[11595:166012] obj ==5
    2015-11-08 10:55:19.879 NSPredicateDemo[11595:166012] obj ==5
    */
    
    }
    
    
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 20"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name > 'abc' && age > 10"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name > 'abc' OR age > 10"];
    
    
    /
    /根据账号找到对应的名字;
    - (void)testPredicateDefinition:(NSMutableArray *)totalArray selectAccount:(NSString *)account withBlock:(void (^)(sswConversationModle *modle))block{
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account=%@",account];
    NSArray *temp = [totalArray filteredArrayUsingPredicate:predicate];
    [temp enumerateObjectsUsingBlock:^(sswConversationModle *modle, NSUInteger idx, BOOL * _Nonnull stop) {
    block(modle);
    }];
    }
    
    
    
    /
    /根据账号找到对应的名字;
    
    - (void)getPredicateDefinition:(NSMutableArray *)totalArray selectAccount:(NSString *)account withBlock:(void (^)(sswConversationModle *modle))block{
    
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account=%@",account];
        NSArray *temp = [totalArray filteredArrayUsingPredicate:predicate];
        [temp enumerateObjectsUsingBlock:^(sswConversationModle *modle, NSUInteger idx, BOOL * _Nonnull stop) {
            block(modle);
        }];
    }
    
    -(void)sortByBusinessId{
        
        //根据business_id 降序排列
        
        NSSortDescriptor* sortByA = [NSSortDescriptor sortDescriptorWithKey:@"business_id" ascending:NO];
        
        m_notice_list=[[NSMutableArray alloc]initWithArray:[m_notice_list sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortByA]]];
        
        
        
        if (m_notice_list.count > 0) {
            
            //最大ID
            
            NoticeModle* firstModle = m_notice_list[0];
            
            m_max_tag_id = firstModle.business_id;
            
            //最小ID
            
            NoticeModle* lastModle = m_notice_list[m_notice_list.count-1];
            
            m_min_tag_id = lastModle.business_id;
            
            NSUserDefaults* defaults= [NSUserDefaults standardUserDefaults];
            
            [defaults setValue:m_max_tag_id forKey:maxKey];
            
            [defaults setValue:m_min_tag_id forKey:minKey];
            
            [self saveToFile];
            
        }
        
    }
    

    实现搜索

    (void)filterContentForSearchText:(NSString*)searchText{
    
    //我这里把没有 文本时读取数据库 的情形都写在一起了
        if (searchText.length == 0 && [[TCRecondBase selectHistroySearchGames] count] > 0) {
            self.type = HistroyType;
            self.datasArry = [TCRecondBase selectHistroySearchGames];
    
        }else{
            self.type = SearchResultType;
        }
        //检测输入的是不是拼音
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^[A-Za-z]*$"];
        NSMutableArray* resultArry = [NSMutableArray array];
    //是拼音则匹配以输入的拼音开头的且不区分大小写的游戏名
        if ([predicate evaluateWithObject:searchText]) {
    
            NSPredicate *predict = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] %@",searchText];
            NSArray* spallArry = [_allSpalls filteredArrayUsingPredicate:predict];
            for (NSString* str in spallArry) {
    
                NSInteger index = [_allSpalls indexOfObject:str];
    
                [resultArry addObject:[_allNames objectAtIndex:index]];
            }
    //输入的是数字或者汉字 则匹配名字中包含输入字符的游戏名
        }else{ 
            NSPredicate *predict = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchText];
    //或者使用 @"name LIKE[cd] '*%@*'"    //*代表通配符
            resultArry = [_allNames filteredArrayUsingPredicate:predict].mutableCopy;
        }
        self.searchResultArry = resultArry;
        [self.histroyTableView reloadData];
    }
    //NSPredicate功能很强大,更多谓词匹配语法自行百度NSPredicate的使用
    

    使用谓词实现分组排序

       NSMutableSet *set = [NSMutableSet set];
                
                //利用set不重复的特性,得到有多少组,根据model中的exchangeShortTime字段
                [self.contacts enumerateObjectsUsingBlock:^(Contacts * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
                    [set addObject:item.shengxiao];
                }];
                
                /*此时,set里面已经存储了可以分为组数*/
                
                //接下来需要用到NSPredicate语法进行筛选
                __block NSMutableArray *arr = [NSMutableArray array];
                [set enumerateObjectsUsingBlock:^(NSString * _Nonnull zodiac, BOOL * _Nonnull stop) {
                    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"shengxiao = %@", zodiac];
                    NSArray *tempArr = [NSArray arrayWithArray:[self.contacts filteredArrayUsingPredicate:predicate]];
                    [arr addObject:tempArr];
                }];
    
    1.NSString 对象  
      
    NSArray  *array =@["123", @"234" , @"345"];  
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", "2"];  
    NSArray *filterdArray = [array filterdArrayUsingPredicate:predicate];  
    NSLog(@"%@", filterdArray );  
    //output : @"123", "234"  
      
    2.含有属性的对象  
      
    @interface Person: NSObject   
    {  
        NSString *_name;  
        NSString *_telephone;  
        NSInteger _id;  
    }  
      
    @property (nonatomic, copy) NSString *name;  
    @property (nonatomic, copy) NSString *telephone;  
    @property (nonatomic, assign) NSInteger id;  
      
    @end  
    //  
      
    1).等于查询  
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", "Ansel"];   
    NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];  
      
    2).模糊查询  
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@", @"A"]; //predicate只能是对象  
    NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate]; 
    

    相关文章

      网友评论

          本文标题:ios-Predicate介绍

          本文链接:https://www.haomeiwen.com/subject/wjzmjxtx.html