Memory cycles = strong0 ^ strong1 pointers; (strong1 == weak) ? @"Yes" : @"No"

51 Views Asked by At

well I want to find out why there is a memory cycle in this case:

@property (nonatomic, strong) NSArray *myBlocks;

// and the method

[self.myBlocks addObject: ^(){
    [self doSomething];
}]; 

well the block has a strong pointer to self because self is referenced inside it. And we point to myBlocks strongly. But why does myBlocks have a strong pointer to the block?

2

There are 2 best solutions below

0
On BEST ANSWER

But why does myBlocks have a strong pointer to the block?

An NSArray holds strong references to it's elements.

In general, you instantiate an array by sending one of the array... messages to either the NSArray or NSMutableArray class. The array... messages return an array containing the elements you pass in as arguments. And when you add an object to an NSMutableArray object, the object isn’t copied, (unless you pass YES as the argument to initWithArray:copyItems:). Rather, a strong reference to the object is added to the array.

more here

0
On

Your class which is self has a strong reference to myBolcks:

@property (nonatomic, strong) NSArray *myBlocks;

And this is taken from apple doc:

Blocks maintain strong references to any captured objects, including self...

In your scenario self has strong pointers to block and block by capturing self has also strong pointer do self which is retain cycle, which create memory leak.

To break this cycle use weak pointer to self before you pass it to a block.