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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With