Recursive Blocks in Objective-C leaking in ARC

后端 未结 3 780
生来不讨喜
生来不讨喜 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 14:58

    Without further context information, I can say this:

    You are leaking that block because you are copying it and not releasing it elsewhere. You need to copy it to move it to the heap, that's ok. But the way you've chosen is not entirely ok.

    A correct way to do it is to store it as some object instance variable, copy it, and then release it inside dealloc. At least, that's a way to do it without leaking.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-16 15:04

    Aaron,

    As your code appears to be single threaded, why are you copying the block? If you don't copy the block, you don't have a leak.

    Andrew

    0 讨论(0)
提交回复
热议问题