简体   繁体   English

如何在viewDidLoad方法内部的UIViewController中初始化方法

[英]how to initialize methods in a UIViewController inside of a viewDidLoad method

There is a method for creating data. 有一种创建数据的方法。 This method needs to be called only once. 此方法仅需要调用一次。 So currently this is the structure: 所以目前这是结构:

var dataCreated : Bool? = false



override func viewDidLoad() {
    super.viewDidLoad()

    if dataCreated! == false {
        createData()
        self.dataCreated = true
    }
}

Is this the right way to ensure createData() method is called only once? 这是确保createData()方法仅被调用一次的正确方法吗? Thank you. 谢谢。

Since you only want createData to be called once per instance of your view controller, then using viewDidLoad is a good place to call it. 由于只希望对视图控制器的每个实例调用一次createData ,因此使用viewDidLoad是调用它的好地方。 Further, since viewDidLoad is only called once per instance of the view controller, there is no need for the dataCreated property. 此外,由于viewDidLoad在每个视图控制器实例中仅被调用一次,因此不需要dataCreated属性。 You can remove that. 您可以删除它。

override func viewDidLoad() {
    super.viewDidLoad()

    createData()
}

Another option would be to call createData from the init method of the view controller. 另一个选择是从视图控制器的init方法调用createData This depends on what createData needs to access. 这取决于createData需要访问什么。 If the createData method needs access to views and outlets, then you must use viewDidLoad . 如果createData方法需要访问视图和出口,则必须使用viewDidLoad

Your code will work as expected. 您的代码将按预期工作。 You might prefer to compute whether data has been created by checking for its existence rather than tracking a separate Boolean variable. 您可能更喜欢通过检查数据是否存在来计算数据是否已创建,而不是跟踪单独的布尔变量。 Although this will work too. 虽然这也可以。

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

相关问题 如何在Swift 4的UIViewController中转换viewDidLoad方法? swift 4不推荐使用initialize() - How to swizzle viewDidLoad method in UIViewController in swift 4? initialize() is deprecated in swift 4 如何在iOS上的静态库中调用UIViewController :: viewDidLoad? - How to call UIViewController::viewDidLoad from inside a static library on iOS? 我们是否必须在viewDidLoad中或UIViewController中的viewDidLoad外部初始化属性? - Do we have to initialize properties in viewDidLoad or outside of viewDidLoad in UIViewController? 如何在viewDidLoad方法中增加UIView的大小? - How to increase size of UIView inside viewDidLoad method? 在初始化方法完成之前调用的UIViewController viewDidLoad - UIViewController viewDidLoad called before init method is complete UIViewController.View.Window 在 ViewDidLoad 方法中为 null - UIViewController.View.Window is null in ViewDidLoad method UIViewController中的ViewDidLoad方法 - 什么时候被调用? - ViewDidLoad method in UIViewController - when does it get called? UIViewController viewDidLoad - UIViewController viewDidLoad 如何在viewDidLoad之前初始化UITableView? - How to initialize UITableView before viewDidLoad? UIViewController方法viewDidLoad / viewWillHappen-视图帧大小检测 - UIViewController Methods viewDidLoad/viewWillHappen - view frame size detection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM