Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to use __weak self inside UIAnimationBlocks in ARC?

Do we need to use __weak self inside UIAnimation Blocks as given below? Whether it will create retain cycle issue if we are not specifying self as weak?

[UIView animateWithDuration:animationDuration                        delay:0                      options:UIViewAnimationCurveEaseInOut                   animations:^{         [self doSomething];     } completion:^(BOOL finished) {         if (finished) {             [self doSomething];         }     }]; 

I am also confused in the following scenario. Any thoughts on this? please share your comments.

[self.navController dismissViewControllerAnimated:animated                                         completion:^{                                                       [self doSomething];                                                   }]; 

Should we use weak self here?

like image 566
arango_86 Avatar asked Apr 21 '15 11:04

arango_86


People also ask

Should I always use weak self?

Using [weak self] is only required within situations in which capturing self strongly would end up causing a retain cycle, for example when self is being captured within a closure that's also ultimately retained by that same object.

Do you need weak self in UIView animate?

You don't need to use [weak self] in static function UIView. animate() You need to use weak when retain cycle is possible and animations block is not retained by self. For more information: Automatic Reference Counting.

Why do we use weak self?

In Swift, [weak self] prevents closures from causing memory leaks in your application. This is because when you use [weak self], you tell the compiler to create a weak reference to self. In other words, the ARC can release self from memory when necessary.

Why do you generally create a weak reference when using self in a block?

For many of us, it's best practice to always use weak combined with self inside closures to avoid retain cycles. However, this is only needed if self also retains the closure. By adding weak by default you probably end up working with optionals in a lot of cases while it's actually not needed.


1 Answers

This is not a retain cycle. A retain cycle would be

self -> block -> self 

In this case we have

animation framework -> block block -> self 

where the first retain is only temporary - the block gets released when the animation ends. Even if a retain cycle happens, it will be only temporary and it won't prevent object deallocation.

like image 98
Sulthan Avatar answered Oct 07 '22 00:10

Sulthan