After some research I found out my app was using way too much energy because of several UIView
animations throughout the app, where I was capturing the related UIViewController
in the completion block, without making a weak reference to it.
So actually, I changed this:
func animate() {
UIView.animate(withDuration: 0.3, animations: {
self.label.alpha = 0.5
}) { _ in
self.animate()
}
}
Into this :
func animate() {
UIView.animate(withDuration: 0.3, animations: {
self.label.alpha = 0.5
}) { [weak self] _ in
self?.animate()
}
}
However, I would like to know if I need to do the same with the animation
block (the self.label.alpha = 0.5
one) ?
Thank you for your help
The contents of your block are performed on the main thread regardless of where you call [UIView animateWithDuration:animations:] . It's best to let the OS run your animations; the animation thread does not block the main thread -- only the animation block itself.
UIView. animate runs on the main thread and is asynchronous.
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.
duplicated of Is it necessary to use [unowned self] in closures of UIView.animateWithDuration(...)?
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.
There is an article on medium about where [weak self]
may and may not be needed
For more information:
Automatic Reference Counting
Closures
There might be another issue for the energy problem.
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