0

I am making my own app and I save a label and saving it by clicking the player1button and I then get it back in the view did load. The problem is that after I get it back it won't let me change it again and when I try to click the goalUp button it comes up with the error: "thread 1: EXC_BAD_INSTRUCTION". It says this error on the first line under viewDidLoad. Please help!

@IBOutlet var goal: UILabel!

@IBAction func player1button(sender: AnyObject) {
    NSUserDefaults().setValue(goal.text!, forKey:"firstGoal")
}

var goal1 = 0

@IBAction func goalUp(sender: AnyObject) {
    goal1++
    goal.text = "\(goal1)"
}

override func viewDidLoad() {
    super.viewDidLoad()
    goal1 = Int((NSUserDefaults().objectForKey("firstGoal") as? String)!)!
    goal.text = (NSUserDefaults().objectForKey("firstGoal") as? String)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571

3 Answers3

0

Try setObject instead of setValue in player1button method:

NSUserDefaults.standardUserDefaults().setObject(goal.text!, forKey:"firstGoal")

UPD

Writing data to NSUserDefaults is not always immediate. Call synchronize to save it right now without delay.

NSUserDefaults.standardUserDefaults().setObject(goal.text!, forKey:"firstGoal")
NSUserDefaults.standardUserDefaults().synchronize()
shpasta
  • 1,913
  • 15
  • 21
  • Check is everything ok in your casting sting to int, see here http://stackoverflow.com/questions/24115141/swift-converting-string-to-int – shpasta Jan 22 '16 at 00:41
  • No need to force synchronize – Leo Dabus Jan 22 '16 at 00:54
  • 1
    The line it's crashing on has a complex mix of stuff going on. Temporarily split it out into separate pieces so you can see which is actually causing the problem. This should make it easier to troubleshoot. – Michael Jan 22 '16 at 01:02
0

It says this error on the first line under viewDidLoad. Dou you mainsuper.viewDidLoad()? Maybe you should check your super.

Peike Luo
  • 1
  • 2
0

It might have to do with the way you are passing goal1 around, sometimes as an Int but sometimes as a String. Choose one and just do that. I think it will be easier to stay using it as an Int (make sure you save it as an Int as well). Anytime you want to convert the Int to String you can use String(intValue).

EDIT: I just ran this succesfully

      var goal1String = ""
//    var goal1 = 0

override func viewDidLoad() {
    super.viewDidLoad()
 // goal1 = Int((NSUserDefaults().objectForKey("firstGoal") as? String)!)!
      goal1String = String(NSUserDefaults().objectForKey("firstGoal"))
      print(goal1String)
      goal.text = (NSUserDefaults().objectForKey("firstGoal") as? String)
}


   @IBOutlet var goal: UILabel!

   @IBAction func player1button(sender: AnyObject) {
    NSUserDefaults().setValue(goal.text!, forKey:"firstGoal")
   }



  @IBAction func goalUp(sender: AnyObject) {
       goal1++
       goal.text = "\(goal1)"
   }

Make goal1 a String and not an Int

MikeG
  • 3,745
  • 1
  • 29
  • 51