Ios ViewDidLoad中的快速更改方法
我正在尝试使用以下代码更改ViewDidLoad中的方法: 课堂声明:Ios ViewDidLoad中的快速更改方法,ios,swift,viewdidload,Ios,Swift,Viewdidload,我正在尝试使用以下代码更改ViewDidLoad中的方法: 课堂声明: var nextValue: Int! 在ViewDidLoad中: if nextValue == nil { print("Hi") } else if nextValue == 2 { print("Hello") } 最后,这个函数改变了nextValue的值: func buttonAction(sender: AnyObject) { self.performSegueWithId
var nextValue: Int!
在ViewDidLoad中:
if nextValue == nil {
print("Hi")
} else if nextValue == 2 {
print("Hello")
}
最后,这个函数改变了nextValue的值:
func buttonAction(sender: AnyObject) {
self.performSegueWithIdentifier("nextView", sender: self)
nextValue = 2
}
当我从“nextView”返回到第一个视图时,nextValue应该是2,但它是零。我做错了什么?您对视图生命周期的理解是错误的 首先,在类声明中用nil值声明变量。 然后,在viewDidLoad方法中检查其值,最后通过一些按钮操作更改其值 然而,当您通过segue到nextView离开视图控制器屏幕时,您的firstView将被取消分配,并且当您再次表示它时,循环将返回到声明级别。因为您将变量值声明为nil,所以它将始终显示nil值 如果要保留其值,则需要将其保存到其他位置,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")
}
当您向后移动时,如何检查该值是否仍然为零?在viewDidLoad中?在进入下一个视图时,您使用的是哪种序列?虽然这个答案的基础是正确的,但严格来说并不正确
firstView
将不会被解除分配,但您建议使用ViewWillDisplay是正确的: