سؤال

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?

هل كانت مفيدة؟

المحلول

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?

نصائح أخرى

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

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).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top