Recursive Block Retain Cycles

前端 未结 6 976
心在旅途
心在旅途 2020-12-13 04:44

Will this lead to any sort of retain cycle? Is it safe to use?

__block void (^myBlock)(int) = [^void (int i)
{
    if (i == 0)
        return;

    NSLog(@\"         


        
6条回答
  •  天命终不由人
    2020-12-13 05:37

    There's a simple solution that avoids the cycle and the potential need to prematurely copy:

    void (^myBlock)(id,int) = ^(id thisblock, int i) {
        if (i == 0)
          return;
    
        NSLog(@"%d", i);
        void(^block)(id,int) = thisblock;
        block(thisblock, i - 1);
      };
    
    myBlock(myBlock, 10);
    

    You can add a wrapper to get the original type signature back:

    void (^myBlockWrapper)(int) = ^(int i){ return myBlock(myBlock,i); }
    
    myBlockWrapper(10);
    

    This becomes tedious if you want to extend it to do mutual recursion, but I can't think of a good reason to do this in the first place (wouldn't a class be clearer?).

提交回复
热议问题