You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否使用NSPredicate将属性与通配符数组进行比较?

关于NSPredicate匹配通配符数组的问题

你给出的这种实现方式不可行。NSPredicate的格式语法并不支持LIKE IN这种写法,直接运行代码会触发运行时异常,提示格式字符串无效。

正确实现方式

下面提供两种可靠的实现方案:

方案一:拼接OR条件格式字符串

遍历通配符数组,将每个元素转换为独立的LIKE条件,再用OR连接:

NSArray *wildcards = @[@"Jerry*", @"George*", @"Elaine*"];
NSMutableArray *predicateClauses = [NSMutableArray array];
for (NSString *wildcard in wildcards) {
    [predicateClauses addObject:[NSString stringWithFormat:@"property LIKE %@", wildcard]];
}
NSString *predicateFormat = [predicateClauses componentsJoinedByString:@" OR "];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat];

方案二:使用NSCompoundPredicate组合子谓词

这种方式更安全,避免手动拼接字符串可能出现的语法错误:

NSArray *wildcards = @[@"Jerry*", @"George*", @"Elaine*"];
NSMutableArray *subPredicates = [NSMutableArray array];
for (NSString *wildcard in wildcards) {
    NSPredicate *subPredicate = [NSPredicate predicateWithFormat:@"property LIKE %@", wildcard];
    [subPredicates addObject:subPredicate];
}
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];

内容的提问来源于stack exchange,提问作者ThinkCL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 14:34:52