Objective c 如果调用对象被解除分配,调度线程会发生什么情况?
我正在将图像异步加载到UITableView中的单元格中。代码如下所示:Objective c 如果调用对象被解除分配,调度线程会发生什么情况?,objective-c,uitableview,grand-central-dispatch,Objective C,Uitableview,Grand Central Dispatch,我正在将图像异步加载到UITableView中的单元格中。代码如下所示: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // after getting the cell.. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// after getting the cell..
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *imageUrl = [someMethodToGetImageUrl];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL imageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:imageData];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
});
});
}
我的问题是,如果此tableView在触发分派之后,但在线程完成尝试设置单元格的映像之前被解除分配(例如,从navigationController堆栈中弹出),会发生什么情况。手机也会被解除分配,尝试对手机进行操作会导致崩溃,不是吗
上面的代码让我崩溃了。如果我进入这个tableView,然后立即退出,我会在线路上发生崩溃:
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
如果我将其更改为:
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
碰撞消失了,这对我来说真的没有意义。有人能给我解释一下为什么会这样吗?谢谢。任何可能使块超出其原始范围的例程都需要复制它<代码>调度异步()执行 复制块时,块将保留其引用的任何对象指针变量。如果块以实例变量的形式隐式访问
self
,它将保留self
。它保存这些引用,直到它自己被释放
在您的示例中,
cell
、imageData
、indepath
和tableView
都会保留到块完成为止。是否启用了ARC?属性是如何定义的(例如弱、强、复制等)是的,ARC已启用,我不知道第二个问题的答案。我的代码段中没有一个变量是属性。它们只是通过[alloc]方法分配的。我是这里的初学者,这回答了你的问题吗?我确实有一个属性,我在这个代码片段中简化了/模糊了它。方法someMethodToGetImageUrl
实际上是声明为(非原子,强)的属性对象中的实例方法。