[英]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.