我的应用程序 App 构造函数和 onStart 方法有什么区别? [英] What's the difference between my application App constructor and the onStart method?

查看:33
本文介绍了我的应用程序 App 构造函数和 onStart 方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的课程:

public partial class App : Application
{

    public static DataManager db;

    public App()
    {
        InitializeComponent();
        MainPage = new Japanese.MainPage();  // 1
    }

    public static DataManager DB
    {
        get
        {
            if (db == null)
            {
                db = new DataManager();
            }
            return db;
        }
    }

    protected override void OnStart()
    {
        App.DB.InitData(); // 2
    }

它在第一次运行时给我一个问题,因为 InitData 设置了表格,但需要在设置表格之前运行的 Japanese.MainPage().

It's giving me a problem on first run in that the InitData sets up tables but the Japanese.MainPage() which needs tables runs before the tables have been set up.

似乎还没有创建所需的表.

Seems like the tables that are needed are not yet created.

将 InitData 移动到 App 构造函数中是否合理?

Would it be reasonable to move the InitData into the App constructor?

推荐答案

每个平台都调用 LoadApplication 来创建 Xamarin.Forms 应用程序的实例.你可以在例如看到这个iOS 上的 AppDelegate 类:

Each platform calls LoadApplication to create an instance of your Xamarin.Forms App. You can see this in e.g. the AppDelegate class on iOS:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();   

    // Init additional components

    LoadApplication(new App());    
    return base.FinishedLaunching(app, options);
}

正如您在那时所看到的,Xamarin Forms 本身已初始化并创建了应用程序的新实例.App 类在每个特定于平台的项目中被实例化,并传递给 LoadApplication 方法,该方法在 MainPage 加载并向用户显示时.

As you can see at that point Xamarin Forms itself is initialized and a new instance of your application is created. The App class is instantiated in each platform-specific project and passed to the LoadApplication method which is when the MainPage is loaded and displayed to the user.

由于您使用的 MainPage 在其构造函数中使用来自数据库的数据,因此您在 OnStart 中的初始化在生命周期中为时已晚,因为它发生在 MainPage 正在创建.将您的数据库初始化移动到 App 构造函数(在 MainPage 分配之前)将适用于您的场景.请确保在平台特定代码中的 LoadApplication 调用之前初始化您使用的任何需要初始化的其他组件.

Since the MainPage you use uses data from the DB in its constructor your initialization in OnStart is too late in the lifecycle because it happens after the MainPage being created. Moving your DB initialization to the App constructor (before the MainPage assignment) would work in your scenario. Do ensure that any additional components you use that need to be initialized are initialized before the LoadApplication call in the platform specific code.

这篇关于我的应用程序 App 构造函数和 onStart 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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