gpt4 book ai didi

ios - NSPredicate 将 NIL 字符串作为任何字符处理

转载 作者:行者123 更新时间:2023-11-28 21:36:44 24 4
gpt4 key购买 nike

我有一个 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 语句来格式化谓词并将 Nil 值处理为'任何'。这里的问题是,如果 searchStr 为 Nil,我还希望将其处理为“ANY”。在 Nil 的情况下,我试图将其设置为空字符串,但它不起作用。有什么方法可以在不对每种情况使用任何 If 语句的情况下实现这一点(9 个 if 语句太多了)?

最佳答案

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

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,
]
];

关于ios - NSPredicate 将 NIL 字符串作为任何字符处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com