3

I have a ViewController class as shown below:

class ViewController {

    var viewModel = ViewModel()

    viewDidLoad() {
        self.viewModel.showAlert = { [weak self] in
            self?.alert()
        }
    }

    func alert() {
        // alert logic
    }
}

Here is the ViewModel class

class ViewModel {
    var showAlert: (() -> Void)?
}

Now, does this create a strong reference cycle or not?

And if this creates one, then what to use - weak or unowned?

Savan Kavaiya
  • 33
  • 1
  • 5

1 Answers1

2

This does not create a strong reference cycle, because you used weak self.

ViewController holds a strong reference to ViewModel. ViewModel holds a strong reference to a closure. The closure holds a weak reference to the ViewController:

VC ---strong---> ViewModel
 ^                    |
 |                   strong
 |                    v
  --------weak-----closure

As long as ViewController is deallocated (this happens when you dismiss it for example), ViewModel will be as well.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • if weak is not used then there is a strong reference cycle, Am I correct? – Savan Kavaiya Apr 01 '18 at 10:45
  • Thanks. And what is preferable here? Weak or unowned? I think ViewModel and ViewController both have same lifetime so it's safe to use unowned instead of weak. Your thoughts? – Savan Kavaiya Apr 01 '18 at 10:49
  • @SavanKavaiya yeah I suppose. Note that if something else is holding a strong reference to the closure, you should use weak, since the closure can exist without the VC. – Sweeper Apr 01 '18 at 10:53