[英]dispatch_async going in infinite loop
正在开发一个应用程序,其中我必须从JSON获取数据并在UITableView中显示。 获取数据是在后台进行的。 但这似乎陷入无限循环。
任何帮助将不胜感激。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
queue = dispatch_queue_create("com.events.app", NULL);
dispatch_async(queue, ^{
[self load];
//Need to go back to the main thread since this is UI related
dispatch_async(dispatch_get_main_queue(), ^{
// store the downloaded image in your model
Events *evObj = [eventsArray objectAtIndex:[indexPath row]];
NSLog(@"evObj = %@",evObj);
cell.textLabel.text = evObj.eName;
cell.detailTextLabel.text = @"Detailed Text";
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]
withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView endUpdates];
});
});
// Configure the cell...
return cell;
}
之所以进入循环是因为发送-reloadRowsAtIndexPaths:withRowAnimation:
将触发UITableView
向您的数据源询问另一个带有-tableView:cellForRowAtIndexPath:
单元格-tableView:cellForRowAtIndexPath:
如果要异步更新单元,则必须更新直接的UI元素,但要避免重新加载整个单元。 如果事情没有自动更新,则可以在更新后发送-setNeedsDisplay
或-setNeedsLayout
。
只需删除所有异步调用:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(cell == nil) {
/// load the cell.
}
// store the downloaded image in your model
Events *evObj = [eventsArray objectAtIndex:[indexPath row]];
NSLog(@"evObj = %@",evObj);
cell.textLabel.text = evObj.eName;
cell.detailTextLabel.text = @"Detailed Text";
return cell;
}
只需移动[self load];
到代码的其他部分,例如viewDidLoad
。
区分数据部分和ui部分。
即
呼叫[self load];
方法一次或多次。 最好的位置是viewDidLoad方法左右。
重新加载数据并将其呈现在uitableview中的实现可能看起来像这样(使用GCD)
dispatch_queue_t queue = dispatch_queue_create("com.events.app", NULL);
dispatch_async(queue, ^{
[self load];
//Need to go back to the main thread since this is UI related
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableview reloadData];
//don't forget to release your queue
dispatch_release(queue);
});
});
从rckoenes复制- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {}
方法的实现,您就可以完成;)
但请记住一件事。 您第一次抛出的代码会造成很大的开销,每次调用此方法时,您都需要下载,解析和设置数据,在uitableview加载自身时,至少要在开始时加载3次,然后每次滚动时,其调用次数将达到您可以在屏幕上看到很多行/单元格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.