Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to use [unowned self] in closures of UIView.animateWithDuration(...)?

    UIView.animateWithDuration(1,         animations: { [unowned self] in             self.box.center = self.boxTopRightPosition         },         completion: { [unowned self] completed in             self.box.hidden = true     }) 

Is it necessary to avoid memory leak?

like image 633
WildCat Avatar asked Nov 19 '14 14:11

WildCat


People also ask

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.

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:] .


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.

like image 91
Kirsteins Avatar answered Oct 01 '22 07:10

Kirsteins


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.

like image 38
Pablo A. Avatar answered Oct 01 '22 07:10

Pablo A.