为什么我的可选变量在视图出现后变为null?

时间:2015-12-28 19:38:09

标签: swift uiviewcontroller

我目前正在研究一个Swift应用程序并遇到了这样一个问题:我在应用程序中使用的数据在运行时在某个时刻变为零。我有一个问题,我正在创建的数据暂时存在,然后似乎在屏幕完成显示后解除分配。虽然我可以在每次需要时重新加载数据,但这似乎是效率最低的方法。以下是正在发生的事情的代码示例:

var activeProgram:LumeProgram? { didSet{
    if let _ = activeProgram {
        print("activeProgram exists")
    } else {
        print("activeProgram doesn't exists")
    }
} } // Custom Object Type
var activeDay:LumeProgramDay? // Custom Object Type

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    activeProgram = SomeProgram.initTestProgram()
    activeDay = activeProgram!.getCurrentDay()

    printVariables("ViewWillAppear")
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

   printVariables("ViewDidAppear")
}

调用此代码后,我发现viewWillAppear存在数据,但viewDidAppear不存在数据。有谁知道是什么原因引起的?

ViewWillAppear输出:

--- ViewWillAppear ---
Optional("Nutrition Program") [None]
Phase [Optional(1)]: Optional("Learn") - Optional("Welcome - we’re glad you’re here! Our current focus is learning about your diet. What have you eaten today?")
Lume Program Day: Optional(2)
Main [Insight]: Optional("Day_14_insight.xml")
Sub [None]: nil
Lume Program Day: Optional(1)
Main [Article]: Optional("Day_13_article.xml")
Sub [Quiz]: Optional("Day_13_quiz.xml")
Lume Program Day: Optional(3)
Main [Article]: Optional("Day_15_article.xml")
Sub [Challenge]: Optional("Day_15_challenge.xml")
----------------
Lume Program Day: Optional(1)
Main [Article]: Optional("Day_13_article.xml")
Sub [Quiz]: Optional("Day_13_quiz.xml")
----------------

ViewDidAppear输出:

--- ViewDidAppear ---
nil [None]
Warning: There are no phases in this program.
----------------
Lume Program Day: nil
Main [None]: nil
Sub [None]: nil
----------------

使用添加的didSet调用,我只看到它被调用一次,并且它返回该对象确实存在。该行只写一次,我没有看到任何声明它不存在的调用。我可以添加另一个变量调用,例如didNullify或didEmpty吗?

0 个答案:

没有答案