1

I use Xcode 5 and have some code

@interface Controller {
    __weak IBOutlet UIView *someView;
}

@implementation Controller {

- (void)doSomething
{
    [UIView animateWithDuration:0.5 animations:^{
        someView.hidden = YES;
    }];
}

- (void)doSomething1
{
    [UIView animateWithDuration:0.5 animations:^{
        [self doSomething];
    }];
}

Why the retain cycle warning not thrown there? Should I use weak references on self every time I use self in blocks?

Also I enabled Implicit retain of self within blocks warning and it gave me 100 warnings with advice to write self->ivar.prop (not ivar.prop) in blocks. Should I do so after that warning is disabled by default?

efpies
  • 3,625
  • 6
  • 34
  • 45

3 Answers3

4

Why the retain cycle warning not thrown there?

The block retains you, but you don't retain the block. It'll be destroyed after animation is complete. So, no cycles.

Should I use weak references on self every time I use self in blocks?

If your block doesn't get destroyed automatically (e.g. a recurring timer), then you should.

Should I do so after that warning is disabled by default?

Depends upon the context. Again, if your blocks live for a long time, you might want to declare non-retained weakSelf.

But basically you're fine if your blocks don't get saved somewhere.

See also How do I avoid capturing self in blocks when implementing an API?

Community
  • 1
  • 1
ilya n.
  • 18,398
  • 15
  • 71
  • 89
  • Thanks for clarification. I missed that block is retained only if it is stored. – efpies Sep 27 '13 at 11:57
  • What does it mean for a block to be "long lived"? All blocks have a finite number of lines of code, so it will eventually exit. – Pwner Feb 17 '15 at 21:19
3

This is not a retain cycle. This is two methods calling each other in a loop. A retain cycle happens when two object instances have strong (retained) references to each other that are never broken, and those two objects remain in memory unnecessarily.

Example with code: Retain cycle in ARC

Community
  • 1
  • 1
bneely
  • 9,083
  • 4
  • 38
  • 46
0

Should I use weak references on self every time I use self in blocks?

Absolutely not. Blocks retain captured object pointers for a reason -- to keep the objects alive until so that they'll still be there when the block is run. If there is no retain cycle and there is no other thing keeping a reference to the object pointed to by self, it could be deallocated before the block is run (asynchronously, for example).

newacct
  • 119,665
  • 29
  • 163
  • 224