在ViewDidLoad期间ViewModel为null [英] ViewModel is null during ViewDidLoad

查看:144
本文介绍了在ViewDidLoad期间ViewModel为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在iOS中开始使用MvvmCross.

I am getting started with MvvmCross in iOS.

public class MainView : MvxTabBarViewController
{
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        var vm = (MainViewModel)this.ViewModel;
        if (vm == null)
            return;
    }
}

将断点设置为访问ViewModel的行,向我显示ViewModel为空.

Setting a breakpoint to the line where access the ViewModel, shows me, that ViewModel is null.

我可以通过在构造函数中调用ViewDidLoad()来解决此问题.然后,ViewModel在构造函数调用期间为null,但在默认的ViewDidLoad调用中有效.但这似乎是一种解决方法.有人可以帮忙吗?

I can workaround this by calling ViewDidLoad() in the constructor. Then, ViewModel is null during the constructor call, but valid in the default ViewDidLoad call. But that looks like a workaround. can anybody help?

推荐答案

我猜这里的问题将特定于TabBarViewController的构造方式.

I'm guessing here the problem here will be specific to the way that TabBarViewController is constructed.

ViewDidLoad是一种虚拟方法,它在首次访问View时被称为.

ViewDidLoad is a virtual method and it is called the first time the View is accessed.

对于TabBarViewController,这是在iOS基本View构造函数期间发生的-即,它发生在之前类本身已调用其构造函数的地方.

In the case of TabBarViewController this happens during the iOS base View constructor - i.e. it occurs before the class itself has had its constructor called.

解决这个问题的唯一方法是添加对ViewDidLoad中情况的检查,并在类构造函数中再次调用ViewDidLoad.

The only way around this I've found is to add a check against the situation in ViewDidLoad, and to make a second call to ViewDidLoad during the class constructor.

您可以在行动N-25中看到它-

You can see this in action N-25 - https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/976ede3aafd3a7c6e06717ee48a9a45f08eedcd0/N-25-Tabbed/Tabbed.Touch/Views/FirstView.cs#L17

类似的东西:

public class MainView : MvxTabBarViewController
{
    private bool _constructed;

    public MainView()
    {
            _constructed = true;

            // need this additional call to ViewDidLoad because UIkit creates the view before the C# hierarchy has been constructed
            ViewDidLoad();
    }

    public override void ViewDidLoad()
    {
        if (!_constructed)
            return;

        base.ViewDidLoad();

        var vm = (MainViewModel)this.ViewModel;
        if (vm == null)
            return;
    }
}

这篇关于在ViewDidLoad期间ViewModel为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆