Recursive Blocks in Objective-C leaking in ARC

后端 未结 3 804
生来不讨喜
生来不讨喜 2020-12-16 14:49

So I\'m using recursive blocks. I understand that for a block to be recursive it needs to be preceded by the __block keyword, and it must be copied so it can be put on the

3条回答
  •  孤街浪徒
    2020-12-16 15:04

    Ok, I found the answer on my own...but thanks to those who tried to help.

    If you're referencing/using other blocks in a recursive block, you must pass them in as weak variables. Of course, __weak only applies to block pointer types, so you must typedef them first. Here's the final solution:

        typedef void (^IntBlock)(int);
    
        IntBlock __weak Log = ^(int i){
            NSLog(@"log sub %i", i);
        };
    
        __block void (^LeakingBlock)(int) = ^(int i){
            Log(i);
            if (i < 100) LeakingBlock(++i);
        };
        LeakingBlock(1);
    

    The above code doesn't leak.

提交回复
热议问题