Is it necessary to use [unowned self] in closures of UIView.animateWithDuration(...)?
No, it is not needed in this case. animations
and completion
are not retained by self
so there is no risk of strong retain cycle.
Well, "necessary" isn't the same as "recommended". If your question is if it's necessary then @Kirsteins' response is fine, however imagine the situation where you want to animate something in your view controller after some work, but your view controller has been released (because it is not in the view hierarchy anymore or any other reason). In this case, if you don't use [weak self]
, your view controller won't get released until finishing the animation because you are retaining it in the animation block, but does it make sense to keep it retained until animating something which is not in the view anymore?
So, in few words, you don need to use a weak
reference to self when animating UIKit, however, you don't need to keep your view retained if it's released, because an animation with no view doesn't make sense, so using weak
is a good option.
No it's not needed. As Kirsteins says:
No, it is not needed in this case. animations and completion are not retained by self so there is no risk of strong retain cycle.
But lhmgrassi says:
As soon as it be deallocated, the deinitializer will be called and the completion will never be executed.
I don't think this is true. The completion block will always be called. And if you use a strong self your object won't be deallocated until the completion block is executed.
However, if you use a [weak self]
, your object is not (temporary) retained by the completion block and might be deallocated before the completion block is fired. The completion block is still fired but self
is already nil
.
If you use a [unowned self]
in your completion handler, you object might also be deallocated before the completion handler is called, which could result in a crash!
I've made an example illustrating this.
Full source can be found on Github