简体   繁体   English

iOS / swift - swift中UIViewController中的常量

[英]iOS / swift - constants in UIViewController in swift

Suppose I have a view model that my controller uses for asking some data or functionality, that view model will Never changes when I instantiated once, right? 假设我有一个我的控制器用来询问某些数据或功能的视图模型,那个视图模型在我实例化一次时永远不会改变,对吧? but in view controllers I navigate with perform segue and so on, I have no access to initializer then I can't use some thing like this: 但在视图控制器中,我使用perform segue等导航,我无法访问初始化程序,然后我不能使用这样的东西:

let myViewModel: MyViewModel

then I have to use this instead: 然后我必须改用它:

var myViewModel: MyViewModel!

and I have no good feeling about this, can anyone suggest a good solution? 我对此没有好感,有人能建议一个好的解决方案吗? tnx mates :) tnx队友:)

That's totally fine, same for your IBOutlets. 这对你的IBOutlets来说完全没问题。 From the moment you instantiate the ViewController until you set up the model, it's value is nil . 从实例化ViewController到设置模型的那一刻起,它的值就是nil that means it's not a constant even though you don't change it through the lifecycle of the ViewController. 这意味着它不是一个常量,即使你没有在ViewController的生命周期中改变它。

When view controllers are loaded from storyboard, you have no control over initialization (since the controller is not initialized by you), therefore there is nothing else you can do. 从故事板加载视图控制器时,您无法控制初始化(因为控制器未由您初始化),因此您无法执行任何其他操作。 The other options are similar and there is no real advantage to either of them. 其他选项类似,其中任何一个都没有真正的优势。 It's a subjective decision: 这是一个主观决定:

You could declare the variable as a normal optional 您可以将变量声明为普通可选项

var myViewModel: MyViewModel?

but if the controller really cannot work without data being set, I prefer to use ! 但如果没有数据设置控制器真的无法工作,我更喜欢使用! myself because not setting the data model should be a fatal error. 我自己因为没有设置数据模型应该是一个致命的错误。

In some cases you can also go with a default value, eg: 在某些情况下,您还可以使用默认值,例如:

var myViewModel = MyViewModel()

My data setters usually look like this: 我的数据设置器通常如下所示:

var model: Model! {
   didSet {
       loadViewIfNeeded() // to force view be loaded and viewDidLoad called
       updateUI() // set UI values from the data model     
   }   
}

You can use var declaration if you want to change the ViewModel after instantiation. 如果要在实例化后更改ViewModel,可以使用var声明。

Also in the segue function, you can have access to the viewModel instance, if it defined as a class property of the class in which the segue function is also written. 同样在segue函数中,如果viewModel实例定义为也在其中编写segue函数的类的类属性,则可以访问该模型。

Creating an implicitly unwrapped instance of viewModel in the segue function is a bad idea. 在segue函数中创建一个隐式解包的viewModel实例是个坏主意。

var myViewModel: MyViewModel!

This can lead to crashes. 这可能导致崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM