On Apr 12, 2012, at 12:04 PM, Scott Andrew wrote:

> I have a question about retain cycles with ARC and blocks.
> 
> I have the following code: 
> 
>    __weak MyViewController* controller = self;
> 
>    [UIView animateWithDuration:.25 animations:^{
>        controller.alpha = 0;
>    }
>     completion:^(BOOL finsihed) {
> 
>       [controller showState];
>     }];
> 
> 
> 
> -(void) showState {
>       self.textView.text = self.stateText;
> }
> 
> I have a question about what happens when I use self in showState. DId i just 
> cause a reference counting issue where I now have an extra retain on self and 
> it's not going to be cleaned up?

No.  The compiler looks at the code _in the block_ to know what the block 
should retain.  It doesn't (for this purpose) look inside the -showState 
method.  It can't even reliably know for sure that the call to -showState in 
the block refers to that implementation of -showState.  For example, this code 
could all be called from a superclass which overrides -showState.

> The WWDC video say to use weak pointers to self in the block otherwise there 
> could be retain cycle issues. This is an example. The utility functions are 
> actually quite larger and called from multiple places. I'm not creating the 
> strong refrence via a variable because these blocks won't be called if self 
> doesn't exist.

For this case, you don't even have to worry about referencing self in the 
blocks directly.  You don't need to use the weak copy, controller.  First, the 
object is not itself retaining the blocks.  So, if the blocks retain self, 
that's still not a retain cycle.  Second, the blocks will be disposed of when 
the animation completes.  So any reference they hold on self is released when 
that happens.

Regards,
Ken


_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to