【问题标题】:When to weak and when to strong reference for nested block in block块中嵌套块的弱引用和强引用
【发布时间】:2014-11-26 11:20:47
【问题描述】:

我正在我的代码块中寻找保留周期。我的UITableViewController 中有以下代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //[...] Not important code.
    __weak ELParkingLocationTVC *weakself = self; // Required? (1)
    cell.completionBlock = ^ {
        __strong ELParkingLocationTVC *strongSelf = weakself; // Required? (2)
        __weak ELParkingLocationTVC *weak2self = weakself; // Required? (3)
        [strongSelf dismissViewControllerAnimated:YES completion:^{
            __strong ELParkingLocationTVC *strong2self = weak2self; //Required? (4)
            ELMenuHistoryTVC *menuTVC = [strong2self.navigationController.viewControllers firstObject];
            [menuTVC.parentTabBarController moveToTab:ELMapViewControllerIndex completion:^(BOOL finished) {
                ElMainMapViewController *mainMapViewController = menuTVC.parentTabBarController.viewControllers[ELMapViewControllerIndex];
                //ELCustomParkplace *customParkplace = [strong2self parkplaceAtIndex:indexPath.row]; //(5)
                [mainMapViewController moveToCoordinate:customParkplace.coordinate];
            }];
        }];
    };
}

并有以下问题:

  1. 我需要哪个__weak 和哪个__strong 参考?我确定我必须使用第 1 和第 2,但我真的不确定第 3 和第 4。
  2. 我可以在这里使用@strongify@weakify 吗?
  3. 我想我不需要第 (5) 行,但我不确定。

任何建议、链接或好的评论将不胜感激!

【问题讨论】:

标签: ios objective-c iphone objective-c-blocks weak-references


【解决方案1】:

您确实需要对单元格完成处理程序进行弱引用,因为您有一个引用循环:self > UITableView > UITableViewCell > self

您不需要使用__strong 限定符。默认情况下,变量是强引用。

动画和过渡完成处理程序不需要弱引用,因为这些块会在过渡完成后立即释放,但在这种情况下,它们不能使用 self,因为它们嵌套在无法捕获self 的块。

所以保留weakSelfstrongSelf,并在所有嵌套块中使用相同的strongSelf 变量。

【讨论】:

    猜你喜欢
    • 2013-06-10
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多