【发布时间】:2021-09-23 06:01:27
【问题描述】:
我有一个 UITableView,它显示了音乐库中的所有歌曲,效果很好。但是,当我开始在搜索栏中输入以缩小搜索结果时,应用程序立即崩溃。就像我一按键盘上的一个字母,它就会崩溃。我尝试过修改我的textDidChange: 方法,但无论如何它总是崩溃。我不确定我做错了什么,有人可以帮忙吗?谢谢。
标题:
@interface PTTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (strong,nonatomic)UITableView* tableView;
@property (strong,nonatomic)UISearchBar* searchBar;
@end
ViewController.m:
#import "PTTableViewController.h"
@implementation PTTableViewController
MPMediaQuery *songsQuery;
NSArray *songsArray;
NSMutableArray *filteredArray;
NSMutableArray *songTitlesArray;
-(void)viewDidLoad{
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width - 75,150) style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.view addSubview:_tableView];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0,320,44)];
self.searchBar.delegate = self;
self.searchBar.placeholder = @"Search";
self.tableView.tableHeaderView = self.searchBar;
songsQuery = [MPMediaQuery songsQuery];
songsArray = [songsQuery items];
songTitlesArray = [[NSMutableArray alloc] init];
for (MPMediaItem *item in songsArray) {
[songTitlesArray addObject:[item valueForProperty:MPMediaItemPropertyTitle]];
}
filteredArray = [[NSMutableArray alloc] init];
filteredArray = [songTitlesArray copy];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return filteredArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
cell.textLabel.text = [filteredArray objectAtIndex:indexPath.row];
return cell;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSLog(@"search changed");
[self performSelectorInBackground:@selector(helper) withObject:nil];
}
-(void)helper{
[filteredArray removeAllObjects];
if ([self.searchBar.text isEqualToString:@""]){
filteredArray = [songTitlesArray copy];
} else {
for (NSString *object in songTitlesArray){
if ([object rangeOfString:self.searchBar.text].location == NSNotFound){
NSLog(@"string not found");
} else {
NSLog(@"string found");
[filteredArray addObject:object];
}
}
} [self.tableView reloadData];
}
@end
【问题讨论】:
-
那是因为你要从filteredArray中删除所有元素而不更新表格视图?
-
什么是崩溃信息?
-
我实际上是在越狱设备上的 SpringBoard 中运行这段代码,所以当“应用程序”崩溃时,我的意思是设备重新启动/软重启?奇怪的是,没有生成崩溃报告。
-
你在后台调用助手,所以
[self.tableView reloadData]也在后台调用。 UI 中的主线程应该如何处理这个问题?首先要尝试的是,将 reloadData 包装在 GCD 块中,并改为寻址主线程以进行重新加载。因为可能有一个没有条目的表,这不是一个错误,这是一个功能,但当你的线程搞砸时仍然毫无意义。 -
它仍然在主线程上崩溃。我让它在后台运行的原因是因为如果在主线程上调用键盘也会滞后。
标签: ios objective-c uitableview crash uisearchbar