NSPredicate将NIL字符串作为任意字符处理

时间:2015-11-10 09:56:14

标签: ios objective-c nspredicate

我有NSPredicate看起来像这样:

NSPredicate *predicateSearch;

    if ([category_array count]>0 && [location_array count]>0) {
        predicateSearch =[NSPredicate predicateWithFormat:@"category_id IN %@ AND location_id IN %@ AND company_title CONTAINS %@",category_array,location_array,searchStr];
    }
    else if ([category_array count]>0){

         predicateSearch =[NSPredicate predicateWithFormat:@"category_id IN %@ AND company_title CONTAINS %@",category_array,searchStr];
    }
    else if([location_array count]>0){

        predicateSearch = [NSPredicate predicateWithFormat:@"location_id IN %@ AND company_title CONTAINS %@",location_array,searchStr];
    }

    [fetchRequest setPredicate:predicateSearch];

由于NSPredicate无法处理Nil值,因此我使用此If-Statement格式化谓词并将Nil值处理为' ANY'。 这里的问题是我还希望searchStr被处理为' ANY'如果是Nil。 我试图在Nil的情况下将其设置为空字符串,但它不会起作用。 有没有办法在不对每个案例使用任何If语句的情况下实现这一点(9个if语句太多了)?

1 个答案:

答案 0 :(得分:2)

使用复合谓词。例如,根据您发布的内容:

NSPredicate *categoryPredicate = (category_array.count > 0)
    ? [NSPredicate predicateWithFormat:@"category_id IN %@", category_array]
    : [NSPredicate predicateWithValue:YES];

NSPredicate *locationPredicate = (category_array.count > 0)
    ? [NSPredicate predicateWithFormat:@"location_id IN %@", location_array]
    : [NSPredicate predicateWithValue:YES];

NSPredicate *searchPredicate = (searchStr.length > 0)
    ? [NSPredicate predicateWithFormat:@"company_title CONTAINS %@", searchStr]
    : [NSPredicate predicateWithValue:YES];

NSCompoundPredicate *predicate =
   [NSCompoundPredicate
    andPredicateWithSubpredicates:@[                                            
                                    categoryPredicate,
                                    locationPredicate,
                                    searchPredicate,
                                   ]
   ];