bgolson
bgolson

Reputation: 3500

Paranoid about iOS Blocks and Retain Cycles

I've become a little paranoid with blocks and the possibility of creating a retain cycle. I'm using a block based version of the UIAlertView class which allows you to use blocks instead of delegate methods. I use a lot of these Alertviews, so I'm often calling into instance methods that do a lot of heavy lifting.

Would the assignments I make in the method someInstanceMethod cause a retain cycle?
(I am using ARC for memory management.)

__weak id weakSelf = self;
[doWorkAndThen:^{
   [weakSelf someInstanceMethod];
}];

-(void) someInstanceMethod{
    //will either of the assignments below cause a retain cycle?
    self.iVar = @"data";
    [self setIvar:@"data";
}

Upvotes: 2

Views: 653

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185653

No. -someInstanceMethod is not a block. The fact that you're calling it from one is irrelevant. Only references inside the block itself can cause retains, and since your only reference inside your block is a __weak variable you're fine.

Incidentally, if you really want to ease your mind, you should modify your block-based UIAlertView class to throw away all the blocks when the view is dismissed. This way even if you do create a retain cycle, it will be broken automatically as soon as the alert view goes away.

Upvotes: 8

Related Questions