ios - 在初始化第一个 View Controller 之前运行代码(基于 Storyboard的应用程序)

标签 ios uiviewcontroller uistoryboard appdelegate

我的应用程序每次启动时都需要执行一些清理任务——删除本地存储的旧数据,然后才会显示初始 View Controller 。

这是因为初始 View Controller 在初始化时加载现有数据,并将其显示在 TableView 中。

我设置了几个断点,发现初始 View Controller 的初始化程序 (init?(coder aDecoder: NSCoder)) before application(_ :didFinishLaunchingWithOptions) - 准确地说,甚至在 application(_:**will**FinishLaunchingWithOptions) 之前。

可以将清理代码放在 View Controller 初始化程序的最顶部,但我想将清理逻辑与任何特定屏幕分离。 该 View Controller 可能有一天最终不是初始 View Controller 。

覆盖应用程序委托(delegate)的 init() 方法并将我的清理代码放在那里确实完成了工作,但是......

问题:

难道没有更好/更优雅的方式吗?


Note: For reference, the execution order of the relevant methods is as follows:

  1. AppDelegate.init()
  2. ViewController.init()
  3. AppDelegate.application(_:willFinishLaunchingWithOptions:)
  4. AppDelegate.application(_:didFinishLaunchingWithOptions:)
  5. ViewController.viewDidLoad()

澄清:

清理任务并不冗长,也不需要异步运行:相反,我更希望我的初始 View Controller 在它完成之前甚至不被实例化(我知道如果启动时间过长,系统将终止我的应用程序。但是,它只是删除一些本地文件,没什么大不了的。)。

我问这个问题主要是因为,在 Storyboard 出现之前,应用程序启动代码如下所示:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];

    // INITIAL VIEW CONTROLLER GETS INSTANTIATED HERE 
    // (NOT BEFORE):
    MyViewController* controller = [[MyViewController alloc] init];

    self.window.rootViewController = controller;

    [self.window makeKeyAndVisible];
    return YES;
}

...但是现在,因为主 Storyboard 加载发生在幕后, View Controller 在任何应用委托(delegate)方法运行之前初始化。

在寻找需要将自定义代码添加到我的初始 View Controller 的解决方案。

最佳答案

我不确定是否有更优雅的方式,但肯定有一些其他方式......

I'd prefer if my initial view controller isn't even instantiated until it completes

这不是问题。您所要做的就是从 Info.plist 中删除一个 UIMainStoryboardFileNSMainNibFile 键,它告诉 UIApplicationMain应该加载什么 UI。随后,您在 AppDelegate 中运行“清理逻辑”,完成后,您将自己启动 UI,如示例中所示。

替代解决方案是创建 UIApplicationMain 的子类,并在加载 UI 之前在其中运行清理。

请参阅下面的应用生命周期:

iOS App Life Cycle

关于ios - 在初始化第一个 View Controller 之前运行代码(基于 Storyboard的应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35054284/

相关文章:

ios - 每次将应用程序推回前台时刷新 tableView 的最有效方法是什么?

ios - 如何强制 "Respect Language Direction"从 RTL 到 LTR,反之亦然

swift - ViewController 未按预期执行 segue

iPhone重新加载表数据

ios - 在 XCode 4+ 中创建/编辑子类模板

ios - AppDelegate 在我添加 firebase 时出错

ios - 将 cornerRadius 和 setbackgroundimage 设置为 UIButton

ios - 我可以在我的 View 中添加一个计时器以转到下一个 View 吗?

ios - 为什么我的某些推送 Storyboard 片段不显示 peek 和 pop 选项?

ios - 在 UIStoryboard 中向 UIScrollView 的 subview 添加约束的奇怪行为