-1

Still trying to get the hang of retain cycles when using blocks. My question is.. which of the following (if any) would cause retain cycles?

1

[self.someProperty runSomeBlock:^{
   [self.someOtherProperty doSomething];
}];

2

[self.someProperty runSomeBlock:^{
   [self doSomething];
}];

3

[self.someProperty runSomeBlock:^{
   [someObject runAnotherBlock:^{
      [self.someProperty doSomething];
   }];
}];

4

[self.someProperty runSomeBlock:^{
   [someObject runAnotherBlock:^{
      [self.someOtherProperty doSomething];
   }];
}];

Thanks!

Community
  • 1
  • 1
Jiho Kang
  • 2,482
  • 1
  • 28
  • 38

1 Answers1

1

None of them, on the face of it. The thing that causes a retain cycle with a block is e.g. when the thing you hand the block to persists and retains it (over time) and you retain that thing over time, and the block mentions you — and there's no obvious evidence that that would be happening here.

In other words, it's really no different from the basic thing that always causes a retain cycle: A retains B but B retains A. But in your code, I see no evidence that anyone is retaining anyone.

In any case, if all the objects just execute their blocks instantly when they are handed them, there's nothing to worry about in the first place, since it's only persistence that is the problem.

It sounds like you're just way over-thinking this.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • If you want to see an actual danger case, read my discussion here: http://www.apeth.com/iOSBook/ch12.html#_unusual_memory_management_situations This points out a couple of danger cases and explains very clearly _why_ they are danger cases, i.e. it traces the persistence / retention story so that you can see the cycle. Note that none of these are immediate-execution cases; these are all blocks expressing something an object _will_ perhaps do at some indeterminate time in the future, and therein lies the beginning of the danger... – matt Sep 02 '14 at 02:22
  • One case could be: If you retain the block during the whole lifetime of your object (e.g., store the block in an ivar of `self`) **and** reference `self` inside the block (instead of, say, using a "weak self" reference), then you will have a retain cycle. – Nicolas Miari Sep 02 '14 at 02:28