Blocks and ARC


#1

I read on StackOverflow that with ARC we no longer need to use block_release or block_copy on a block that will be used outside of its defining scope; a regular copy will suffice to move it to the heap, and it will be automagically released like any other object. Is this correct?


#2

Yep! ARC takes away that annoyance and Does The Right Thing. The technique for avoiding retain cycles in blocks has changed slightly (by using a __weak pointer to self)


#3

Thanks! Now here’s a followup question. I’ve put together a small test of the scenarios on page 68 where it was necessary to copy a block after defining it. Except they all seem to work perfectly, and I’m wondering if that’s due to ARC again or if I’m just getting lucky?

[code]typedef void (^BoringBlock) (void);

  • (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    BoringBlock blockPtr;

    if (rand() % 1 == 0) {
    blockPtr = ^{ NSLog (@“You are a winner!”); };
    } else {
    blockPtr = ^{ NSLog (@“Please try again!”); };
    }
    blockPtr();

    BoringBlock block2 = [self test2];
    block2();

    BoringBlock blocks[10];
    for (int i = 0; i < 10; i++) {
    blocks[i] = ^{
    NSLog(@“captured %d”, i);
    };
    }

    for (int i = 0; i < 10; i++) {
    blocksi;
    }
    }

  • (BoringBlock)test2 {
    BoringBlock blockPtr = ^{ NSLog (@“Help me”); };
    return blockPtr;
    }[/code]

Output:

2012-10-17 17:01:16.530 test[9750:c07] You are a winner!
2012-10-17 17:01:16.531 test[9750:c07] Help me
2012-10-17 17:01:16.531 test[9750:c07] captured 0
2012-10-17 17:01:16.531 test[9750:c07] captured 1
2012-10-17 17:01:16.532 test[9750:c07] captured 2
2012-10-17 17:01:16.532 test[9750:c07] captured 3
2012-10-17 17:01:16.532 test[9750:c07] captured 4
2012-10-17 17:01:16.533 test[9750:c07] captured 5
2012-10-17 17:01:16.533 test[9750:c07] captured 6
2012-10-17 17:01:16.533 test[9750:c07] captured 7
2012-10-17 17:01:16.534 test[9750:c07] captured 8
2012-10-17 17:01:16.534 test[9750:c07] captured 9