Strong reference loops for closures?

Swift Closure will have a strong reference loop when it refers to itself, like this example:

class Test { var name = "Hello" func doSomething() { {() -> Void in self.name = "otherName" }() } } 

In the previous example, I created a strong reference loop, so I need to fix it like this:

 class Test { var name = "Hello" func doSomething() { {[unowned self] () -> Void in self.name = "otherName" }() } } 

Question: If I refer to self in closing, do I need to use alway unowned self or are there cases when I need to use weak self ?

+7
closures memory-management swift
source share
1 answer

If I relate to myself in closing, should I always use an unoccupied self, or are there cases when I should use a weak self?

None. In most cases, just refer to self usually and do nothing with its memory management. You only need to worry about memory management if there is a danger of holding the loop, and if you do not close the closure somewhere, for example, the "I" property, there is no such danger.

You can easily prove this by adding a deinit implementation:

 class Test { var name = "Hello" func doSomething() { {() -> Void in self.name = "otherName" }() } deinit { println("bye") } } 

Now create an instance of Test and immediately release it:

 func testTest () { let t = Test() } 

You see a β€œdate” in the console, proving that the instance was released in good condition. There was no "strong reference cycle" in this code. Your fears are unfounded.

[By the way, you are using the word "closure" incorrectly. Each Swift function is a closure. If the problem with the save loop was simply due to the use of the word self in closure, every Swift function would be susceptible to this problem - and obviously this is not so. The place where the weak and unowned self comes into play is in an anonymous function - and only, as I said, if this anonymous function itself is also stored by self .]

+11
source share

All Articles