[swift-users] retain cycle non-obvious when assigning method to closure
Joshua Scott Emmons
skia at skia.net
Sun Jan 17 13:06:20 CST 2016
There's a test case demonstrating what I'm about to talking about: https://gist.github.com/jemmons/6f668006fa2712a84807
But here's the nut of it. Given a class like:
class Foo {
var handler: (()->Void)?
func noop(){}
...
}
If somewhere in this class I do something like:
handler = { self.noop() }
I've created a retain cycle because handler holds a strong reference to a closure which holds a strong reference to self which holds a strong reference to a closure that…
In fact, my understanding is Swift's requirement that self be called out here explicitly is to highlight this danger.
Swift makes it easy to fix the problem with a capture list:
handler = { [unowned self] in self.noop() }
So far, so good. But what if I do something daft like assign noop directly:
handler = noop
This causes a retain loop for all the same reasons as our original example, but there's no self call-out to warn us of impending doom, and no support for some kind of capture list to fix the issue.
Is there any possibility of requiring "self" here? As in: "handler = self.noop" for example? And is there any way of specifying how we want self to be retained here?
Cheers,
-jemmons
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160117/810e5c61/attachment.html>
More information about the swift-users
mailing list