Ios NSPredicate包含包含数字和字母的字符串中的搜索

Ios NSPredicate包含包含数字和字母的字符串中的搜索,ios,core-data,nsstring,nspredicate,Ios,Core Data,Nsstring,Nspredicate,我必须使用NSPredicate搜索一些核心数据对象。但是自定义对象的键name可以同时包含数字和字母。 字符串可能看起来像:john1234 Lennon或Ringo Starr。 我通常会使用谓词NSPredicate*谓词=[NSPredicate predicateWithFormat:@“任何名称都包含[cd]@”,searchString] 但是,如果我搜索John Lennon,谓词不会返回任何内容,因为它无法比较它是否包含字符John Lennon,因为它缺少1234。任何提示我

我必须使用
NSPredicate
搜索一些核心数据对象。但是自定义对象的键
name
可以同时包含数字和字母。 字符串可能看起来像:
john1234 Lennon
Ringo Starr
。 我通常会使用谓词
NSPredicate*谓词=[NSPredicate predicateWithFormat:@“任何名称都包含[cd]@”,searchString]


但是,如果我搜索
John Lennon
,谓词不会返回任何内容,因为它无法比较它是否包含字符
John Lennon
,因为它缺少
1234
。任何提示我可以使用哪种谓词?

您可以标记您的查询,可能非常简单

NSArray *tokens = [querystring componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
然后构造一个复合谓词

NSMutableArray *predarray = [NSMutableArray array];

for(NSString *token in tokens)
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Any name CONTAINS[cd] %@",token];
    [predarray addObject:predicate];
}

NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:predarray];
并将其输入到您的查询中

在现实生活中,我会对每个令牌运行一些验证,以检查它是否会成为有效的谓词,并且不会崩溃或产生安全风险。e、 g带特殊字符,如“*[]”


编辑:更正谓词类型以处理问题情况。

尝试使用LIKE而不是contains,然后可以使用通配符,例如John*Lennon应将以John开头、以Lennon结尾的字符串与任意数量的其他字符进行匹配。你能用吗?相反,如果您希望对匹配的内容进行更多控制,则每个问号只匹配一个字符。

您可以将搜索字符串拆分为字符串数组,然后切换谓词以查找名称中的任何字符串:

NSArray *strings = [searchString componentsSeparatedByString:@" "];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"ANY %@ IN name",strings];

有了这个谓词,谓词什么也找不到。我还尝试了
“anyname IN%@”,字符串
,但没有成功。当我将NSCompoundPredicate更改为
和predicatewithsubpredicates
时,效果非常好。因为
或带有子谓词的预测将给出
任何名称包含[cd]John或任何名称包含[cd]Lennon
。在一个大数据库中,可能有许多替代方案。但是这只会给我一个。这太神奇了!非常感谢。