Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView.animate() : do I need a weak reference to self in the animation block? [duplicate]

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

like image 259
Another Dude Avatar asked Jun 16 '20 12:06

Another Dude


People also ask

Does UIView animate run on the main thread?

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.

Is UIView animate asynchronous?

UIView. animate runs on the main thread and is asynchronous.


2 Answers

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(...)?

like image 67
Cruz Avatar answered Oct 03 '22 16:10

Cruz


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.

like image 44
Omer Faruk Ozturk Avatar answered Oct 03 '22 15:10

Omer Faruk Ozturk