Block recursion and breaking retain cycle

后端 未结 2 1860
清酒与你
清酒与你 2021-02-13 00:03

To better illustrate the question, consider the following simplified form of block recursion:

__block void (^next)(int) = ^(int index) {
    if (index == 3) {
           


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 00:26

    To accomplish the retain-cycle-free recursive block execution, you need to use two block references - one weak and one strong. So for your case, this is what the code could look like:

    __block __weak void (^weak_next)(int);
    void (^next)(int);
    weak_next = next = ^(int index) {
      if (index == 3) {
        return;
      }
      int i = index;
      weak_next(++i);
    };
    next(0);
    

    Note that the block captures the weak block reference (weak_next), and the external context captures the strong reference (next) to keep the block around. Both references point to the same block.

    See https://stackoverflow.com/a/19905407/1956124 for another example of this pattern, which also uses block recursion. In addition, the discussion in the comments section of the following article is relevant here as well: http://ddeville.me/2011/10/recursive-blocks-objc/

提交回复
热议问题