Reputation: 108
Does somebody can explain me how to implement MVVM pattern, when project includes Storyboard?
In many examples I saw that I have to use .xib
files. And init
ViewControllers
like this:
-(instancetype)initWithModelView:(ViewModel *)viewModel{
self = [super init];
if(self){
_viewModel = viewModel;
}
return self;
}
But with Storyboard I cannot init
viewControllers
, storyboard does it for me.
Should I use properties instead?
i.e.
UINavigationController *nav = (UINavigationController *)[self.viewControllers objectAtIndex:0];
HomeViewController *hvc = (HomeViewController *)[nav.viewControllers objectAtIndex:0];
hvc.viewModel = viewModel;
self is UITabBarController
.
Upvotes: 6
Views: 3482
Reputation: 11
I think the best way to handle navigation between views using coordinator or using RX. This will have the separation of concern concept.
Upvotes: 0
Reputation: 736
You can initialize a viewModel
property in prepareForSegue:sender:
method of your UIViewController
Here is a link to a great sample MVVM app C-41 by Ash Furrow
An example of a viewModel
initialization in that app:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
ASHDetailViewController *viewController = segue.destinationViewController;
viewController.viewModel = [self.viewModel detailViewModelForIndexPath:indexPath];
} else if ([[segue identifier] isEqualToString:@"editRecipe"]) {
ASHEditRecipeViewController *viewController = (ASHEditRecipeViewController *)[segue.destinationViewController topViewController];
viewController.viewModel = [self.viewModel editViewModelForNewRecipe];
}
}
Upvotes: 8