Recursive Block Retain Cycles

2019-01-21 17:45发布

问题:

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(@"%d", i);
    myBlock(i - 1);
} copy];
myBlock(10);

myBlock = nil;

回答1:

Your code does contain a retain cycle, but you can break the retain cycle at the end of the recursion by setting myBlock to nil in the recursion base case (i == 0).

The best way to prove this is to try it, running under the Allocations instrument, with “Discard unrecorded data upon stop” turned off, “Record reference counts” turned on, and “Only track active allocations” turned off.

I created a new Xcode project using the OS X Command-Line Tool template. Here's the entire program:

#import <Foundation/Foundation.h>

void test() {
    __block void (^myBlock)(int) = [^void (int i){
        if (i == 0) {
//            myBlock = nil;
            return;
        }
        NSLog(@"myBlock=%p %d", myBlock, i);
        myBlock(i - 1);
    } copy];
    myBlock(10);
}

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        test();
    }
    sleep(1);
    return 0;
}

Then I ran it under the Allocations instrument, with the settings I described above. Then I changed “Statistics” to “Console” in Instruments, to see the program output:

2012-10-26 12:04:31.391 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 10
2012-10-26 12:04:31.395 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 9
2012-10-26 12:04:31.396 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 8
2012-10-26 12:04:31.397 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 7
2012-10-26 12:04:31.397 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 6
2012-10-26 12:04:31.398 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 5
2012-10-26 12:04:31.398 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 4
2012-10-26 12:04:31.399 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 3
2012-10-26 12:04:31.400 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 2
2012-10-26 12:04:31.401 recursiveBlockTest[71789:303] myBlock=0x7ff142c24700 1
<End of Run>

I copied the block address (0x7ff142c24700), changed “Console” to “Objects List”, and pasted the address into the search box. Instruments showed me just the allocation for the block:

The dot under the Live column means the block was still allocated when the program exited. It was leaked. I clicked the arrow next to the address to see the full history of the block's allocation:

Only one thing ever happened with this allocation: it was allocated.

Next I uncommented the myBlock = nil line in the if (i == 0) statement. Then I ran it under the profiler again. The system randomizes memory addresses for security, so I cleared out the search bar and then checked the Console again for the block's address on this run. It was 0x7fc7a1424700 this time. I switched to the “Objects List” view again and pasted in the new address, 0x7fc7a1424700. Here's what I saw:

There's no dot under the Live column this time, meaning that the block had been freed by the time the program exited. Then I clicked on the arrow next to the address to see the full history:

This time, the block was allocated, released, and freed.



回答2:

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?).



回答3:

If you are using ARC, you have a retain cycle, because __block object variables are retained by the block. So the block retains itself. You can avoid it by declaring myBlock as both __block and __weak.

If you are using MRC, __block object variables are not retained, and you should have no problem. Just remember to release myBlock at the end.



回答4:

No, that will not cause a retain cycle. The __block keyword tells the block to not copy myBlock, which would have occurred before assignment causing the application to crash. If this is not ARC the only thing you will need to do is release myBlock after you call myBlock(10).



回答5:

I wanted a solution that gets no warnings, and in this thread https://stackoverflow.com/a/17235341/259521 Tammo Freese gives the best solution:

__block void (__weak ^blockSelf)(void);
void (^block)(void) = [^{
        // Use blockSelf here
} copy];
blockSelf = block;
    // Use block here

His explanation makes perfect sense.



回答6:

Here is a modern solution to the problem:

void (^myBlock)();
__block __weak typeof(myBlock) weakMyBlock;
weakMyBlock = myBlock = ^void(int i) {
    void (^strongMyBlock)() = weakMyBlock; // prevents the block being delloced after this line. If we were only using it on the first line then we could just use the weakMyBlock.
    if (i == 0)
        return;

    NSLog(@"%d", i);
    strongMyBlock(i - 1);
};
myBlock(10);