1
我想改進我的UITableViewController
中的研究。 現在我有一個NSMutableArray
這樣的:改進UISearchDisplayController中的搜索
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];
}
感謝您的答覆,我得到一個錯誤:「太多的參數的方法調用,預計1,在[array addObject:@「SELF like [c]%@,str]上有2個」;「 – Ilario
對不起,編輯了答案。現在試試。 –
錯誤:arraySearch = [arraySearch filteredArrayUsingPredicate:predicate]; 「NSArray」中分配給「NSMutableArray」的不兼容指針類型 – Ilario