在swift 3中创建一个viewcontroller的单例 [英] Create singleton of a viewcontroller in swift 3

查看:1202
本文介绍了在swift 3中创建一个viewcontroller的单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在swift中创建单例类。创建单例类的最简单方法如下:

I know how to create singleton class in swift. The best and easy way to create singleton class is the following:

class Singleton {
    static let sharedInstance = Singleton()
}

但我不需要任何普通类的单例。我需要为viewcontroller类创建单例。所以我正在使用这个代码创建单例

But I don't need singleton for any normal class. I need to create singleton for a viewcontroller class. So I'm using this code create singleton

class AViewController:UIViewController {

    static let sharedInstance = AViewController()

    required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

}

它给我错误 AViewController()

Missing argument for parameter 'coder' in call

$ b中,参数'coder'缺少参数
$ b

看起来它希望我用 init(编码器:NSCoder)进行初始化。但是我应该通过编码器传递什么参数或值?

Looks like it want me to initialize with init(coder: NSCoder). But what parameter or value should I pass through the coder?

推荐答案

如果你真的想为某个场景对应的视图控制器使用单例,你可能会做类似的事情:

If you really wanted to have singleton for a view controller corresponding to some scene, you'd probably do something like:

class SecondViewController: UIViewController {

    static let shared = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Foo")

}

在此示例中,故事板是 Main.storyboard 和故事板有问题的场景的标识符是 Foo 。显然,在你的情况下替换那些适当的值。

In this example, the storyboard was Main.storyboard and the storyboard identifier for the scene in question was Foo. Obviously, replace those values for whatever was appropriate in your case.

那么你调用它的另一个视图控制器可以做类似的事情:

Then your other view controller that was invoking this could do something like:

@IBAction func didTapButton(_ sender: Any) {
    let controller = SecondViewController.shared
    show(controller, sender: self)
}

我不建议为视图控制器提供单例。应在需要时创建视图控制器(及其视图),并在被解除时允许取消分配。而且你正在失去许多故事板的好处(通过它你可以看到场景之间的逻辑流与它们之间的分段)。而且,如果在不同的上下文中使用此视图控制器,则会引发视图控制器层次结构与视图层次结构不同步的问题。我真的不鼓励你为视图控制器使用单例。

I wouldn't recommend singletons for view controllers. View controllers (and their views) should be created when needed and be allowed to be deallocated when they're dismissed. And you're losing many storyboard benefits (by which you see the logical flow between scenes with segues between them). And, if you use this view controller in different contexts, you're inviting problems stemming from the view controller hierarchy falling out of sync with the view hierarchy. I really would discourage you from using singletons for view controllers.

但如果你打算这样做,你可以做类似的事情......

But if you were going to do it, you could do something like that...

这篇关于在swift 3中创建一个viewcontroller的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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