差不多3天了,我还是无法解决这个问题。简单的情况,我想搜索人名(姓名)。
示例:
这是关于if / else的第一部分,我在哪里处理2+个单词的数组。感谢
- (void)searchForText:(NSString*)searchText
{
NSString *searchTextt = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *array = [searchTextt componentsSeparatedByString:@" "];
NSString *firstName = searchTextt;
NSString *lastName = searchTextt;
NSString *firstName2 = searchTextt;
NSString *lastName2 = searchTextt;
NSPredicate *predicate = nil;
if ([array count] > 1) {
firstName = array[0];
lastName = array[1];
firstName2 = array[1];
lastName2 = array[0];
predicate = [NSPredicate predicateWithFormat:@"(guestName CONTAINS[cd] %@ AND guestSurname CONTAINS[cd] %@)", firstName, lastName];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"(guestSurname CONTAINS[cd] %@ AND guestName CONTAINS[cd] %@)", lastName2, firstName2];
NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicate, predicate2]];
self.searchResults = [self.mainarray filteredArrayUsingPredicate:compoundPredicate];
} else {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"guestSurname contains[cd] %@", searchText];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"guestName contains[cd] %@", searchText];
NSPredicate *predicate3 = [NSPredicate predicateWithFormat:@"guestCompany contains[cd] %@", searchText];
NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicate, predicate2, predicate3]];
self.searchResults = [self.mainarray filteredArrayUsingPredicate:compoundPredicate];
}
}
修改
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchString = searchController.searchBar.text;
[self searchForText:searchString];
[_maintable reloadData];
}
答案 0 :(得分:1)
我有一个类似
的数组({ guestName =约翰; guestSurname = Newman; },{ guestName =约翰; guestSurname =稳定; },{ guestName =约翰; guestSurname = Carens; })
我写功能
- (void)searchForText:(NSString*)searchText
{
searchTextt = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *array = [searchTextt componentsSeparatedByString:@" "];
NSString *firstName = searchTextt;
NSString *lastName = searchTextt;
NSPredicate *predicate = nil;
if ([array count] > 1) {
firstName = array[0];
lastName = array[1];
predicate = [NSPredicate predicateWithFormat:@"(guestName CONTAINS[cd] %@ AND guestSurname CONTAINS[cd] %@) OR (guestName CONTAINS[cd] %@ AND guestSurname CONTAINS[cd] %@)", firstName, lastName, lastName, firstName];
} else {
predicate = [NSPredicate predicateWithFormat:@"guestName CONTAINS[cd] %@ OR guestSurnamen CONTAINS[cd] %@", firstName, lastName];
}
NSArray *arrResult = [arr filteredArrayUsingPredicate:predicate];;
}
- (void)updateSearchResultsForSearchController:(UISearchController
*)searchController
{
NSString *searchString = searchController.searchBar.text;
[self searchForText:searchString];
[_maintable reloadData];
}
试试这个。这对我有用我在文本域输入“john”时会得到结果。