1

A got some logic but its not working like I want. Everything is good until coinNumber becames 0 then it restarts to 100 (var coins = 100)

Goal is to starts with 100. Then while you play it has - or + coins and it saves to another variable.

public var coins = 100 // at start got 100 coins


var coinNumber = NSUserDefaults.standardUserDefaults().integerForKey("coins")

func addCoins400() {  // adding 400 coins and save it
        coins = coins + 400

        let CoinsDefault = NSUserDefaults.standardUserDefaults()
        CoinsDefault.setInteger(coins, forKey: "coins")

    }

if coinNumber != 0 {  
            coins = coinNumber
        }

@IBAction func showAnswer(sender: UIButton) {

        if coins >= 50 {
          // I show answer
            coins = coins - 50


            let CoinsDefault = NSUserDefaults.standardUserDefaults()
            CoinsDefault.setInteger(coins, forKey: "coins")
            CoinsDefault.synchronize()
Done
  • 1,088
  • 2
  • 11
  • 19
  • 1
    NSUserDefaults.standardUserDefaults().synchronize() – Asdrubal Aug 04 '16 at 18:41
  • @Asdrubal Probably not. http://stackoverflow.com/a/9647965/2227743 – Eric Aya Aug 04 '16 at 18:49
  • @EricAya "Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes." [Apple iOS Documentation](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html#//apple_ref/occ/instm/NSUserDefaults/synchronize). I don't know the situation OP is using it in which is why I commented & not answered – Asdrubal Aug 04 '16 at 18:56
  • @Asdrubal "You don't need to call it explicitly, iOS already does it at appropriate moments." is the important part and the one relevant to my comment: I'm sure OP doesn't need it - exactly like 99.999% of apps don't need it. :) – Eric Aya Aug 04 '16 at 18:59
  • @EricAya I don't for sure that OP isn't in the 99.999% based on what they posted before the edit ... hence my comment to make sure all possible answers were presented to help OP – Asdrubal Aug 04 '16 at 19:02

1 Answers1

1

Try synchronizing your NSUserDefaults

  public var coins = 100 // at start got 100 coins



var coinNumber = NSUserDefaults.standardUserDefaults().integerForKey("coins")

func addCoins400() {  // adding 400 coins and save it
        coins = coins + 400

        let CoinsDefault = NSUserDefaults.standardUserDefaults()
        CoinsDefault.setInteger(coins, forKey: "coins")
        CoinsDefault.synchronize()
    }

if coinNumber != 0 {  
            coins = coinNumber
        }
AtWork
  • 1,283
  • 1
  • 14
  • 34