以下簡(jiǎn)單的代碼 偶爾會(huì)造成crash
[self.tableView reloadData];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
報(bào)錯(cuò)的Crash
image.png
這· 個(gè)是因?yàn)閞eloadData的 刷新機(jī)制渐裸, 現(xiàn)在看下它的刷新步驟
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
[self.view addSubview:self.tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(@"numberOfRow");
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"heightForRow");
return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"cellForRow");
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
cell.textLabel.text = @"dd";
cell.backgroundColor = [UIColor redColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"begin");
[self.tableView reloadData];
NSLog(@"end");
}
運(yùn)行后的打印順序
image.png
就可以看到 如果你在 reloadData只有寫 對(duì)cell的一些處理 比如滾動(dòng) 或者刪除 就可能引起越界 等一些奇怪的Crash
解決辦法
第一種解決辦法
NSLog(@"begin");
[self.tableView reloadData];
dispatch_async(dispatch_get_main_queue(), ^{
//寫相關(guān)處理Cell的方法 比如 scrollToRowAtIndexPath 等
NSLog(@"end");
});
第二種解決辦法
NSLog(@"begin");
[self.tableView reloadData];
[self.tableView layoutIfNeeded];
//寫相關(guān)處理Cell的方法 比如 scrollToRowAtIndexPath 等
NSLog(@"end");
第三種寫法
NSLog(@"begin");
[self.tableView reloadData];
[CATransaction begin];
[CATransaction setCompletionBlock:^{
//寫相關(guān)處理Cell的方法 比如 scrollToRowAtIndexPath 等
NSLog(@"end");
}];
[CATransaction commit];
這三種執(zhí)行方法的控制臺(tái)打印都是
2019-04-28 11:46:13.183054+0800 testUU[26623:383414] begin
2019-04-28 11:46:13.183602+0800 testUU[26623:383414] numberOfRow
2019-04-28 11:46:13.183948+0800 testUU[26623:383414] cellForRow
2019-04-28 11:46:13.184394+0800 testUU[26623:383414] heightForRow
2019-04-28 11:46:13.184765+0800 testUU[26623:383414] heightForRow
2019-04-28 11:46:13.184976+0800 testUU[26623:383414] heightForRow
2019-04-28 11:46:13.185202+0800 testUU[26623:383414] heightForRow
2019-04-28 11:46:13.185469+0800 testUU[26623:383414] end