Does passing a function belonging to itself cause a hold cycle if it is not in a closure?

If you need to reference self inside a closure, it is recommended that you use it as weak or unowned to prevent a save loop.

If I pass a function belonging to self directly, will the save loop call? Or is it necessary to embed in closure to weaken oneself?

Direct transmission

 UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1, options: .CurveEaseOut, animations: self.view.layoutIfNeeded, // does this cause retain cycle? completion: nil) 

Closing wrap

 UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1, options: .CurveEaseOut, animations: { [unowned self] in self.view.layoutIfNeeded() }, completion: nil) 
+6
source share
2 answers

This should not create a reference loop, but even if everything was fine. The reference cycle will exist only until the animation is completed, after which it will be broken. Creating short-lived reference loops can be useful because it ensures that the target continues to exist for the life of the call. Loops are not inherently a problem. Inevitable cycles are a problem.

There are two reasons why this does not create a loop. Firstly, there is no "cycle". The system will refer to something (moreover, for a second), of course. But where is the link to "a thing that refers to something?" To say this a little more clearly, even if the animation system refers to self , how does self refer to the animation system? There is no cycle.

Another reason there is no loop is because you still don't go through self in the animation system. Walkthrough self.view.layoutIfNeeded . In Swift, this is equivalent to:

 UIView.layoutIfNeeded(self.view) 

You do not miss self here. You are viewing a presentation. Now, the animation system will almost certainly refer to this view until the animation finishes, but it’s fine. This is not a cycle yet.

+3
source

There is no reference loop since self does not commit closing, but if you do not want another strong reference to self , you can use package closure.

If you are sure that self will not be released within the next 0.3 seconds, you can use unowned otherwise weak . (I would use weak to make sure it is not crashing)

+1
source

All Articles