2

I've always been using [weak self] in every callback in the event that the controller unwinds and "self" can become nil.

Is this the right approach?

What are some examples when I should use [unowned self] or neither...assuming "self" is a ViewController that will frequently get unwinded?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • Possible duplicate? http://stackoverflow.com/questions/24011575/what-is-the-difference-between-a-weak-reference-and-an-unowned-reference – Hugues BR Jul 22 '15 at 22:40

1 Answers1

4

If it is possible that the callback will still be called when the self has been deinitialized, using [weak self] is correct. The reason to use [unowned self] would be cases where you know the callback will never be called after self is gone, but strongly capturing self would lead to a retain cycle.

An example of [unowned self] would be a case where the closure's existence depends on the existence of self, then it is clear that if self is gone the closure will be gone as well and won't be called.

Arkku
  • 41,011
  • 10
  • 62
  • 84
  • 1
    To be safe, should I just use [weak self] all the time? Assuming self is a view controller. What would be the effects if I used weak self everywhere? Would memory get released "slower" or something? – TIMEX Jul 22 '15 at 21:15
  • 1
    @TIMEX Well, if you are not sure that `unowned self` is safe in a particular case, use `weak self`. The closure will then be a bit more complex to make (since `weak` makes `self` an optional) and might have a theoretical impact on performance, but given that using a `__weak` reference has been common practice in Objective-C, it's not going to be catastrophic (also, premature optimization =). – Arkku Jul 22 '15 at 21:34