-2

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?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • briefly, because your `myBlocks` array tries to keep your blocks alive – regarding there is nothing else here which does such thing, and the `NSArray` always retains its content. – holex Aug 13 '14 at 11:26
  • But why does it keep the blocks alive? – user3928968 Aug 13 '14 at 11:48
  • you mean the `NSArray`...? the sounds a silly question, regarding if you put something into an array you expected that will in the array later when you tried to access to it – that why the array keeps its items alive. – holex Aug 13 '14 at 11:59
  • aha I got it holex thanks! – user3928968 Aug 13 '14 at 12:05

2 Answers2

0

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

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
0

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.

Greg
  • 25,317
  • 6
  • 53
  • 62