简体   繁体   English

ViewDidLoad中的快速更改方法

[英]Swift change method in ViewDidLoad

I'm trying to change a method in ViewDidLoad with this code: 我正在尝试使用以下代码更改ViewDidLoad中的方法:

In class declaration: 在课堂宣告中:

var nextValue: Int!

And in ViewDidLoad: 在ViewDidLoad中:

if nextValue == nil {
    print("Hi")
}   else if nextValue == 2 {
    print("Hello")
}

And finally this function that changes the value of nextValue: 最后,该函数更改nextValue的值:

func buttonAction(sender: AnyObject) {
    self.performSegueWithIdentifier("nextView", sender: self)
    nextValue = 2    
}

When I move back from "nextView" to the first view nextValue should be 2 but it is nil. 当我从“ nextView”移回第一个视图时,nextValue应该为2,但为零。 What am I doing wrong? 我究竟做错了什么?

Your understanding about view life cycle is wrong. 您对视图生命周期的理解是错误的。

First, you declare your variable with nil value in class declaration. 首先,在类声明中使用nil值声明变量。 then, during viewDidLoad method you check its value, finally you change its value with some button action. 然后,在viewDidLoad方法中检查其值,最后通过一些按钮操作更改其值。

However, when you leave your view controller screen via segue to nextView, your firstView gets deallocated and when you represent it again, the cycle goes back to declaration level. 但是,当您通过segue转到nextView离开视图控制器屏幕时,firstView将被释放,并且当您再次表示它时,循环回到声明级别。 since you declare your variable value as nil, it will always show nil value. 由于您将变量值声明为nil,因此它将始终显示nil值。

if you want to retain its value, you need to save it somewhere else, NSUserDefault seems like a good choice to store its value. 如果要保留其值,则需要将其保存在其他位置,NSUserDefault似乎是存储其值的不错选择。

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

    nextValue = NSUserDefaults.standardUserDefaults().valueForKey("nextValue") as? Int

    if nextValue == nil {
        print("Hi")
    }   else if nextValue == 2 {
        print("Hello")
    }
}

func buttonAction(sender: AnyObject) {
    self.performSegueWithIdentifier("nextView", sender: self)
    nextValue = 2
    NSUserDefaults.standardUserDefaults().setInteger(2, forKey: "nextValue")    
}

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

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