在 IOS 目标 c 中使用搜索栏/过滤过程



谁能帮我找出为什么在搜索栏中输入文本时调用搜索栏委托方法时我无法获取过滤的数组

我的工具栏textDidChange方法

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if(searchText.length == 0){
isFiltered = NO;
}else{
isFiltered = YES;
[filterdArray removeAllObjects];
for(int i = 0; i < [productArray count]; i++){
NSRange textRange;
textRange =[[[[productArray objectAtIndex:i] objectForKey:@"senior_name"] lowercaseString] rangeOfString:[searchText lowercaseString]];
if(textRange.location != NSNotFound){
[filterdArray addObject:[productArray objectAtIndex:i]];
NSLog(@"filterdArrayyyyyyyy:%@",filterdArray);
}
}
}
[self.residentListTableView reloadData];   
}

这是我的productArray

(
{
id = 369;
"room_no" = 101;
"senior_name" = Tim;
},
{
id = 388;
"room_no" = "<null>";
"senior_name" = res444;
},
{
id = 382;
"room_no" = "<null>";
"senior_name" = tt1234;
},......

filterarray返回空

,我想根据"senior_name"过滤表视图

提前谢谢你,

您可以尝试以下代码以获得适当的结果。

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if(searchText.length == 0){
isFiltered = NO;
}else{
isFiltered = YES;
[filterdArray removeAllObjects];
for(int i = 0; i < [productArray count]; i++){
if([[[[productArray objectAtIndex:i] objectForKey:@"senior_name"] lowercaseString] rangeOfString:[searchText lowercaseString]].length>0){
[filterdArray addObject:[productArray objectAtIndex:i]];
NSLog(@"filterdArrayyyyyyyy:%@",filterdArray);
}
}
}
[self.residentListTableView reloadData];   
}

在搜索栏委托方法中添加以下代码-

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSString *textToSearch = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]; // Its better to remove whitespaces & newline characters
isFiltered = textToSearch.length ? YES : NO;
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"self.senior_name MATCHES[cd] %@",textToSearch]; // This predicate will search for exact case-insensitive match. You can change your predicate also. 
filteredArray = [productArray filteredArrayUsingPredicate: searchPredicate];
[filteredArray removeAllObjects];
if (shouldShowSearchResults && filteredArray.count == 0) {        
// Show a view like no search results found        
}
else {
[self.residentListTableView reloadData];
}    
}

在表中查看委托方法添加以下内容-

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (isFiltered ? filteredArray.count : productArray.count);
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:CELL_ID];
if(isFiltered){
// Load data from filteredArray
}else{
// Load data from productArray
}
return cell;
}

适用于此问题的新观众 @shelby 没有在视图中初始化数组DidLoad 他只是宣布它。

经验法则相同

声明NSMutableArray *filterdArray ;这只是声明

初始化[[NSMutableArray alloc]init]OR[NSMutableArray new]

最新更新