MVVM模式和Storyboard iOS

时间:2014-08-13 09:22:47

标签: ios design-patterns mvvm

当项目包含Storyboard时,有人能解释我如何实现MVVM模式吗?

在许多示例中,我看到我必须使用.xib个文件。 init ViewControllers就像这样:

-(instancetype)initWithModelView:(ViewModel *)viewModel{

    self = [super init];

    if(self){

        _viewModel = viewModel;
    }

    return self;
}

但是使用Storyboard我不能init viewControllers,故事板会为我做。 我应该使用属性吗?

UINavigationController *nav = (UINavigationController *)[self.viewControllers objectAtIndex:0];
HomeViewController *hvc = (HomeViewController *)[nav.viewControllers objectAtIndex:0];
hvc.viewModel = viewModel;

自我是UITabBarController

1 个答案:

答案 0 :(得分:8)

您可以使用viewModel

prepareForSegue:sender:方法初始化UIViewController媒体资源

以下是一个很棒的MVVM应用示例C-41 by Ash Furrow

的链接

该应用中的viewModel初始化示例:

- (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];
    }
}