简体   繁体   English

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

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

I am looking for retain cycles in my block in my code. 我在我的代码中寻找我的块中的保留周期。 I have the following code in my UITableViewController : 我的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];
            }];
        }];
    };
}

And have the following questions: 并提出以下问题:

  1. Which __weak and which __strong reference do I need? 我需要哪个__weak__strong参考? I am sure that 1st and 2nd I have to use, but I am really not sure about 3rd and 4th. 我确信第一和第二我必须使用,但我真的不确定第3和第4。
  2. Can I use @strongify and @weakify here? 我可以在这里使用@strongify@weakify吗?
  3. I think I don't need line (5), but I am not sure. 我想我不需要第(5)行,但我不确定。

Any suggestion, link or nice comment will be appreciated! 任何建议,链接或好评都将不胜感激!

You do need a weak reference for the cell completion handler, because you have a reference cycle: self > UITableView > UITableViewCell > self . 您确实需要一个弱引用的单元格完成处理程序,因为您有一个引用循环: self > UITableView > UITableViewCell > self

You do not need to use the __strong qualifier. 您不需要使用__strong限定符。 Variables are strong references by default. 默认情况下,变量是强引用。

You do not need a weak reference for the animation and transition completion handlers, as those blocks are released as soon as the transition completes, but in this case they can't use self because they're nested inside of a block that can't capture self . 您不需要动画和转换完成处理程序的弱引用,因为转换完成后会立即释放这些块,但在这种情况下,它们不能使用self因为它们嵌套在不能阻塞的块中抓住self

So keep weakSelf and strongSelf , and use the same strongSelf variable inside all of the nested blocks. 因此,保持weakSelfstrongSelf ,并在所有嵌套块中使用相同的strongSelf变量。

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

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