gpt4 book ai didi

ios - UITableView从UISearchBar更新结果

转载 作者:行者123 更新时间:2023-12-01 16:13:19 26 4
gpt4 key购买 nike

我有一个带有UISearchBar和UITablevView的ViewController。 tableview只是显示数组中的项目列表,但是我希望它显示带有filteredArrayUsingPredicate的过滤项目列表。我可以使用谓词NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@ OR SELF LIKE[cd] %@", searchText,searchText];来获取过滤后的数组,当我打印过滤后的数组的计数时,项数是正确的。但是,当我尝试在表中显示它时,发生崩溃,并显示以下错误:*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndexedSubscript:]: index 3 beyond bounds [0 .. 2]'
这是搜索栏和填充表格的代码:

@interface ViewController (){
NSMutableArray<NSString*> *_items;
NSMutableArray<NSString*> *_filtered;
bool _searching;
}


@end

@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self->_items = @[@"iphone",@"ipad",@"ipod",@"imac"];
self->_filtered = [[NSMutableArray alloc] initWithArray:self->_items];
self->_table.dataSource = self;
[self->_table setDelegate:self];
[self->_search setDelegate:self];
self->_searching = false;

}
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText{
self->_searching = true;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@ OR SELF LIKE[cd] %@", searchText,searchText];
self->_filtered = [self->_items filteredArrayUsingPredicate:predicate];
NSLog(@"%lu",(unsigned long)[self->_filtered count]);

[self->_table reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self->_items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
if(self->_searching)
cell.textLabel.text = self->_filtered[indexPath.row];
else
cell.textLabel.text = self->_items[indexPath.row];
return cell;
}
@end


似乎导致崩溃的行是这样 [self->_table reloadData];中的 - (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText
在那种方法中,我将search设置为true,在 cellForRowAtIndexPath中,我检查search是否为true,然后显示过滤的结果,否则显示项目。但是我不明白,如果我重新加载数据并告诉它显示过滤后的结果,为什么会发生崩溃。

最佳答案

如果numberOfRowsInSection为true,则应该从_searching返回未过滤的项目计数。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (_searching) {
return _filtered.count;
}

return _items.count;
}

关于ios - UITableView从UISearchBar更新结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58922001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com