Wednesday, May 18, 2022

Weak Self: Closure Rules of Thumb

Christian Tietze:

In Swift, you can weak-ify references to self in escaping closures, and then you need to deal with the case that the reference is gone when the block is called.

Last month, Benoit Pasquier and Chris Downie presented different takes on the problem. That discussion was excellent. It prompted me to take some more time to revisit this problem systematically, and I took away a couple of notes for future-me.

The three popular options as Chris listed them are these:

  1. Do not capture strong reference
  2. Override self with strong reference
  3. Bind strongSelf

As always, either way has its pitfalls.

[…]

[When overriding self, you] can forget weakifying inner closures and accidentally create a retain cycle again!

I think we still see this discussed because nobody has a great solution. There are some common patterns, but they are verbose and still easy to get wrong.

I tend to upgrade self at the top of the closure. For common cases like notifications and timers, I have the caller handle this and pass the strong reference into the closure if it’s not nil.

Previously:

1 Comment RSS · Twitter


... [When overriding self, you] can forget weakifying inner closures and accidentally create a retain cycle again! ...

So true. I still get confused sometimes.

Leave a Comment