我想在UITableViewController
内改进研究。
现在我有NSMutableArray
这样:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"the dog is brown",@"the cat is red",@"the mouse is grey"];
现在,如果我在我的searchbar
中写道:“猫”,表格会显示“猫是红色的”,这是好的。
但如果我写:“猫红”,表格将是空的。
我可以做些什么来改善这个?
所以现在就像进行搜索一样:
-(void)loadArray {
arraySearch = [[NSMutableArray alloc] initWithCapacity:[array count]];
[arraySearch addObjectsFromArray: array];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[arraySearch removeAllObjects];
for (int z=0; z<[array count]; z++) {
if ([[array objectAtIndex:z] rangeOfString:searchText options:NSCaseInsensitiveSearch].location !=NSNotFound) {
[arraySearch addObject:[array objectAtIndex:z]];
}
[self.tableView reloadData];
}
感谢所有人。
我发现了解决方案,我想与您分享:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[arraySearch removeAllObjects];
NSArray *listItems = [searchText componentsSeparatedByString:@" "];
NSMutableArray *arrayPredicate = [NSMutableArray array];
for (NSString *str in listItems) {
if ([str length] > 0) {
NSPredicate *pred = [NSPredicate predicateWithFormat:@"self contains [cd] %@ OR self contains [cd] %@", str, str];
[arrayPredicate addObject:pred];
}
}
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:arrayPredicate];
[arraySearch addObjectsFromArray:[array filteredArrayUsingPredicate:predicate]];
[self.tableView reloadData];
}
答案 0 :(得分:1)
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[arraySearch removeAllObjects];
//Break the sentence into words
NSArray *listItems = [searchText componentsSeparatedByString:@" "];
//Iterate each word and create predicate statement
NSMutableArray *predicatesArray = [NSMutableArray array];
for (NSString *str in listItems) {
[predicatesArray addObject:[NSString stringWithFormat:@"SELF like[c] %@",str]];
}
//Concatenate predicate statements by conditional OR
NSPredicate* predicate = [NSPredicate predicateWithFormat:[predicatesArray componentsJoinedByString:@" OR "]];
//Filter the array against matching predicate
[arraySearch addObjectsFromArray:[array filteredArrayUsingPredicate:predicate]];
[self.tableView reloadData];
}