繁体   English   中英

何时弱到何时对块中的嵌套块进行强引用

[英]When to weak and when to strong reference for nested block in block

我在我的代码中寻找我的块中的保留周期。 我的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参考? 我确信第一和第二我必须使用,但我真的不确定第3和第4。
  2. 我可以在这里使用@strongify@weakify吗?
  3. 我想我不需要第(5)行,但我不确定。

任何建议,链接或好评都将不胜感激!

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

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

您不需要动画和转换完成处理程序的弱引用,因为转换完成后会立即释放这些块,但在这种情况下,它们不能使用self因为它们嵌套在不能阻塞的块中抓住self

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM