-1

I'm trying to change a method in ViewDidLoad with this code:

In class declaration:

var nextValue: Int!

And in ViewDidLoad:

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

And finally this function that changes the value of 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. What am I doing wrong?

Ponchotg
  • 1,195
  • 1
  • 14
  • 25
Mat Koffman
  • 509
  • 1
  • 7
  • 18

1 Answers1

2

Your understanding about view life cycle is wrong.

First, you declare your variable with nil value in class declaration. then, during viewDidLoad method you check its value, finally you change its value with some button action.

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. since you declare your variable value as nil, it will always show nil value.

if you want to retain its value, you need to save it somewhere else, NSUserDefault seems like a good choice to store its value.

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")    
}
Steve Wilford
  • 8,894
  • 5
  • 42
  • 66
seto nugroho
  • 1,359
  • 1
  • 13
  • 20
  • 1
    While the basis of this answer is correct it is not strictly true. `firstView` will **not** get deallocated, but you are correct in recommending to use `viewWillAppear:` – Steve Wilford Nov 30 '15 at 08:34