In the Swift Book it says the closure needs a capture list when the closure is saved in the object as a property. (using Swift 1.2 in a Playground).
A strong reference cycle can also occur if you assign a closure to a property of a class instance, and the body of that closure captures the instance. This capture might occur because the closure’s body accesses a property of the instance, such as self.someProperty, or because the closure calls a method on the instance, such as self.someMethod(). In either case, these accesses cause the closure to “capture” self, creating a strong reference cycle.
However in this code, I am not storing the closure in the object. Yet it appears I need to put the [unowned self] otherwise deinit is never called.
class NamedObject {
var name: String
init(name: String) {
self.name = name
}
func update() {
dispatch_async(dispatch_get_main_queue()) { // [unowned self] in // capture list...uncomment to get deinit to call.
self.name = "foo"
}
}
deinit {
println("\(name) is being deinitialized")
}
}
var hello : NamedObject? = NamedObject(name: "hello")
hello?.name
hello?.update()
hello = nil // force release.
This means that I need to add capture lists to virtually closure in the program because I am almost always referencing self. I want to make sure that I have this right before making such a change. It seems that if that really were necessary, then they would have used a simpler example like the one I have.
Note that this is different than this question: Swift Closures - Capturing self as weak
This is also different than this question, even though the cause is the same, my question was about block ownership and that question was about deinit never being called ever, they are not exactly the same as it has been marked: Deinit method is never called - Swift playground