我想改进我的研究UITableViewController
。现在我有一个NSMutableArray
这样的:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"the dog is brown",@"the cat is red",@"the mouse is grey"];
现在如果我在我searchbar
的例子中写:“猫”,表格将显示“猫是红色的”,没关系。但是如果我写:“cat red”,表格就会是空的。
我能做些什么来改善这一点?
所以就像现在进行搜索一样:
-(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];
}