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 .]
matt
source share