I've been implementing the MVVM paradigm for a while now while adopting ReactiveCocoa in certain parts of the project. I have a simple question about the lifetime of an object related to a view.
Imagine that whenever the View
disappears from the screen, the View
Model needs to update something in an object. Should this updates be called by the ViewController
or can the View
Model observe, for example, the viewWillDisappear Selector in the ViewController
and react to it? Would that be a bad practice?
You use MVVM pattern in order to decouple view (and view controllers, which in Cocoa are also considered a part of the View layer) from the model. That means view model should not know anything about the view controller.
As described in this post, ideally you shouldn't even import UIKit
in your view model.
In other words, a view model should be reusable for displaying the same data in different ways: you may want to display the data in a view controller and a plain UIView
subclass somewhere else (think about having an PersonViewModel
in PersonTableViewCell
and in a PersonDetailsViewController
which is shown after tapping a cell - I think it's a pretty common scenario).
If you somehow observe viewWillDisappear
in the view model, it is tightly coupled to UIViewController
subclasses and can't be used with UIView
subclasses.
Updates to the view model should be called in the view controller in a following way:
- (void)viewWillDisappear:(BOOL)animated
[super viewWillDisappear:animated];
[self.viewModel updateStuff];
}