如何编写一个 nspredicate 来获取包含部分搜索词的记录?
How to write a nspredicate to get records that contains part of the search term?
我如何编写一个谓词来使用这样的搜索字符串过滤掉数据。
用户输入 "red pepper".
这应该return所有记录,包括"red pepper"、"red bell pepper"等
这是我写的
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ingredientName contains[c] %@)" ,self.searchIngrediants.text ];
[fetchRequest setPredicate:predicate];
这只有 return 条包含搜索词的记录,例如 "red pepper"、"belgian red pepper"。
是否可以使用谓词来做到这一点。我正在使用 Objective-c.
如有任何帮助,我们将不胜感激!
为此你需要使用 LIKE
。
NSString *searchStringWithPattern = [self.searchIngrediants.text stringByReplacingOccurrencesOfString:@" " withString:@"*"];
searchStringWithPattern = [NSString stringWithFormat:@"*%@*", searchStringWithPattern];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ingredientName LIKE[cd] %@)" , searchStringWithPattern];
[fetchRequest setPredicate:predicate];
使用正则表达式应该是这样的:
NSString* regex = @"red.*pepper";
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(ingredientName MATCHES %@)", regex];
如果您的输入有 newlines/TABs/... 相应地调整 regex
。
Objective C代码:-
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:@"ingredientName contains[cd] %@",self.searchIngrediants.text];
包含将检查字符是否存在。
Swift 代码:-
var predicate: NSPredicate?
predicate = NSPredicate(format: "ingredientName contains[cd] %@", searchIngrediants.text)
我如何编写一个谓词来使用这样的搜索字符串过滤掉数据。
用户输入 "red pepper".
这应该return所有记录,包括"red pepper"、"red bell pepper"等
这是我写的
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ingredientName contains[c] %@)" ,self.searchIngrediants.text ];
[fetchRequest setPredicate:predicate];
这只有 return 条包含搜索词的记录,例如 "red pepper"、"belgian red pepper"。
是否可以使用谓词来做到这一点。我正在使用 Objective-c.
如有任何帮助,我们将不胜感激!
为此你需要使用 LIKE
。
NSString *searchStringWithPattern = [self.searchIngrediants.text stringByReplacingOccurrencesOfString:@" " withString:@"*"];
searchStringWithPattern = [NSString stringWithFormat:@"*%@*", searchStringWithPattern];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ingredientName LIKE[cd] %@)" , searchStringWithPattern];
[fetchRequest setPredicate:predicate];
使用正则表达式应该是这样的:
NSString* regex = @"red.*pepper";
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(ingredientName MATCHES %@)", regex];
如果您的输入有 newlines/TABs/... 相应地调整 regex
。
Objective C代码:-
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:@"ingredientName contains[cd] %@",self.searchIngrediants.text];
包含将检查字符是否存在。
Swift 代码:-
var predicate: NSPredicate?
predicate = NSPredicate(format: "ingredientName contains[cd] %@", searchIngrediants.text)