能否使用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
相关产品推荐
相关产品推荐

