0

Can someone confirm if the block below is turning into a retain cycle please? Please note the block is being called by SampleClass2 not SampleClass1.

@interface SampleClass1{
    NSArray *_array;
}

@implementation SampleClass1

-(void) doSomething {
    SampleClass2 *sampleClass2 = [[SampleClass2 alloc] init];
    [sampleClass2 doAnother:^(NSArray *anotherArray){
        _array = anotherArray;      // _array is an ivar
    }];
}

@end
Eimantas
  • 48,927
  • 17
  • 132
  • 168
aprofromindia
  • 1,111
  • 1
  • 13
  • 27

2 Answers2

1
  • Does the block retain self? Yes.
  • Does sampleClass2 retain the block? Maybe. It depends on what the doAnother: method does. Without the code, it's impossible to say.
  • Even if we assume that sampleClass2 retains the block, is there a retain cycle? No. There is a connection sampleClass2 -> the block -> self, but nowhere from the code shown is there a connection from self to sampleClass2.
newacct
  • 119,665
  • 29
  • 163
  • 224
0

There only can be a retain cycle when the block is kept around in an ivar or property. We don't see what -[SampleClass2 doAnother:] does with the block, so we don't know.

The block does capture self implicitly by referencing the ivar _array, so there's a chance that a reference cycle is formed. It depends on who retains the SampleClass1 instance and what SampleClass2 does with the block.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • 1
    Whatever you do inside a block won't affect retain cycles outside a block. The only case of retain cycle is when you retain block itself, for example: [self block:^(id smth) { [self function]; Also how you can say "there is a chance" - either there is retain cycle or there's not :) }]; – Grzegorz Krukowski Dec 12 '13 at 16:38
  • 1
    @GrzegorzKrukowski If the `doAnother:` method ends up retaining the block then there will be a reference cycle. – rmaddy Dec 12 '13 at 16:39
  • 1
    Not really - if SampleClass2 retains (copy) a block it will release it after object will be deallocated - and block itself is not retaining SampleClass2 in any place. – Grzegorz Krukowski Dec 12 '13 at 16:41
  • @GrzegorzKrukowski That depends on the ownership graph as a whole. If the block is retained by `sampleClass2` and `sampleClass2` is retained by the `SampleClass1` instance there's a cycle. – Nikolai Ruhe Dec 12 '13 at 17:39