问题描述
[filteredArray filterUsingPredicate:
[NSPredicate predicateWithFormat:@"self BEGINSWITH[cd] %@", searchText]];
filteredArray
包含简单的 NSStrings.[hello, my, get, up, 7, etc...];
filteredArray
contains simple NSStrings. [hello, my, get, up, seven, etc...];
它将给出所有以 searchText
开头的字符串.
It will give all strings that begin with searchText
.
但如果字符串是我的名字是"和searchText = name
等词的组合.NSPredicate
会是什么样子来实现这一点?
But if string will be a combination of words like "my name is", and searchText = name
. What would a NSPredicate
look like to achieve this?
更新:如果我想要 searchText = name
的结果,而不是 searchText = ame
的结果,那该怎么办?也许是这样的:
UPDATE:And how would it have to be if i want to a result with searchText = name
, but not with searchText = ame
? Maybe like this:
[filteredArray filterUsingPredicate:
[NSPredicate predicateWithFormat:
@"self BEGINSWITH[cd] %@ or self CONTENTS[cd] %@",
searchText, searchText]];
但它应该首先显示以 searchText
开头的字符串,并且只在包含 searchText
的字符串之后显示.
But it should first display the strings that begin with searchText
and only after those which contain searchText
.
推荐答案
[NSPredicate predicateWithFormat:@"self CONTAINS[cd] %@", searchText];
问题扩展后编辑
NSArray *beginMatch = [filteredArray filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:
@"self BEGINSWITH[cd] %@", searchText]];
NSArray *anyMatch = [filteredArray filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:
@"self CONTAINS[cd] %@", searchText]];
NSMutableArray *allResults = [NSMutableArray arrayWithArray:beginMatch];
for (id obj in anyMatch) {
if (![allResults containsObject:obj]) {
[allResults addObject:obj];
}
}
filteredArray = allResults;
这将按所需顺序生成结果,而不会出现重复条目.
This will have the results in the desired order without duplicate entries.
这篇关于如何使用 NSPredicate 过滤数组以进行单词组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!