4

I'm implementing a simple Master-Detail app where the Master viewController manages a table view which shows the results of a call to a REST service. The Detail viewController manages a view where I show more information about the item selected in the Master. Common scenario.

I'm trying to apply MVVM pattern. In the Master viewController, I create and initialize its viewModel this way:

lazy private var viewModel: ListViewModel = {
    return ListViewModel()
}()

override func viewDidLoad() {
    super.viewDidLoad()

    initViewModel()
}

private func initViewModel() {
    viewModel.onModelChange = { [weak self] () in
        DispatchQueue.main.async {
            self?.tableView.reloadData()
        }
    }

    viewModel.fetchData()
}

My question is: in the closure provided to the viewModel, should self be weak or unowned instead? I found an example implementing an scenario similar to mine that was setting it to weak, and another one setting it to unowned, so I'm not completely clear.

AppsDev
  • 12,319
  • 23
  • 93
  • 186
  • 1
    Your `viewModel` will never exist without the `self` (view controller). Thus, self will never be nil, you can safely use `unowned`. – Au Ris May 20 '18 at 11:05

3 Answers3

3

Unowned is used when you 100% sure the object won't be deallocated.

weak you then need to take care of its reference count issues.

viewModel.onModelChange = { [weak self] () in
    guard let strongSelf = self else { return }
    strongSelf.tableView.reloadData()
}

I generally do it like this. You then hold a strong reference of self to avoid it being allocated during the block is running.

Tony Lin
  • 922
  • 6
  • 25
3

[unowned self]. This tells your model not to hold a strong reference to ViewController

Apple document states it clearly that:

“Like weak references, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is assumed to always have a value”.

In your case, there is always be ViewController. So benefit of unowned reference is it’s nonoptional. No unwrap required each time it is used

Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
  • 1
    Thanks. As said in a comment below my question also, I think that this would work for my particular scenario, since my "Master" view controller is the root one and its view model won't exist longer than itself. – AppsDev May 20 '18 at 11:39
2

The difference between unowned and weak is that weak is declared as an Optional while unowned isn't. If you know that self will not be nil use unowned, if you don't know: Use weak

barbarity
  • 2,420
  • 1
  • 21
  • 29