使用Swift 3中的UserDefaults保存高分

时间:2017-05-16 20:41:29

标签: swift nsuserdefaults

class ThirdViewController: UIViewController {

var i = 3

var a: Double = 0

var fastestScore:Float = 100000000000000.0

var randomNumberX = Int(arc4random_uniform(375))

var randomNumberY = Int(arc4random_uniform(667))


@IBOutlet weak var fastestScoreLabel: UILabel!

@IBOutlet weak var homeButtonLabel: UIButton!

@IBOutlet weak var finalLabel: UILabel!

@IBOutlet weak var playAgainButtonLabel: UIButton!

@IBOutlet weak var circleImage: UIButton!

@IBOutlet weak var secondTimerLabel: UILabel!

@IBOutlet weak var counterLabel: UILabel!

var timerA = Timer()

var timerB = Timer()

@IBAction func homeButton(_ sender: Any) {

    nextPage = false

}

@IBAction func playAgainButton(_ sender: Any) {

    randomNumberX = Int(arc4random_uniform(375))

    randomNumberY = Int(arc4random_uniform(667))

    homeButtonLabel.isHidden = true

    counterLabel.text = "3"

    i = 3

    timerA = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ThirdViewController.counterFunc), userInfo: nil, repeats: true)

    a = 0

    counterLabel.isHidden = false

    playAgainButtonLabel.isHidden = true

    circleImage.isHidden = true

    finalLabel.isHidden = true

    secondTimerLabel.isHidden = true

    fastestScoreLabel.isHidden = true

}

@IBAction func circleButton(_ sender: Any) {

    fastestScoreLabel.isHidden = false

    circleImage.isHidden = true

    homeButtonLabel.isHidden = false

    timerB.invalidate()

    playAgainButtonLabel.isHidden = false

    var saying = ""

    if a < 0.2 {

        saying = "That's actually pretty good \(a) seconds is pretty fast"

    } else if a >= 0.2 && a <= 0.45 {

        saying = "\(a) seconds is not really that good"

    } else {

        saying = "\(a) seconds? Seriously? Are you even trying?"

    }

    finalLabel.text = saying

    finalLabel.isHidden = false

    if Float(a) < fastestScore {

        fastestScore = Float(a)

        UserDefaults.standard.set(fastestScore, forKey: "Fastest Score")

        let savedFastestScore = UserDefaults.standard.float(forKey: "Fastest Score")

        fastestScoreLabel.text = String(savedFastestScore)

    }


}

func secondTimer() {

    a = a + 0.01

    secondTimerLabel.text = String(a)

}

func counterFunc() {

    if i > 1 {

        i -= 1

        counterLabel.text = String(i)

    } else {

        timerB = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(ThirdViewController.secondTimer), userInfo: nil, repeats: true)

        circleImage.isHidden = false

        self.circleImage.center = CGPoint(x:randomNumberX, y:randomNumberY)

        counterLabel.isHidden = true

        timerA.invalidate()

        secondTimerLabel.isHidden = false

    }

}

override func viewDidLoad() {
    super.viewDidLoad()


    fastestScoreLabel.isHidden = true

    homeButtonLabel.isHidden = true

    playAgainButtonLabel.isHidden = true

    circleImage.isHidden = true

    secondTimerLabel.isHidden = true

    timerA = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ThirdViewController.counterFunc), userInfo: nil, repeats: true)

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

我已经尝试过很多次使用userDefaults尝试在你结束时保存高分,但我似乎无法做到。如果有人知道如何做到这一点我会非常感激lol。

2 个答案:

答案 0 :(得分:0)

当您保存高分时,请确保您拥有的当前分数大于新分数。

假设当前的高分为100

if currentNode.leftChild != self.sentinal:
    newNode = self._put(key, val, currentNode.leftChild)
    return newNode

上面的代码将转到您需要保存高分的功能。也许在你的场景游戏中。

要检索低分,请执行此操作

 var fastestScore = 100 
 var currentScore: Int?


if currentScore < fastestScore { 
          Userdefaults.standard.set(currentScore, forKey: "Fastest Score") 


}

答案 1 :(得分:0)

您仍然无法清楚地解释您所看到的问题,但我的猜测是,您的高分似乎并未在应用重新启动时得到保存。

问题是您在创建fastestScore时将ThirdViewController初始化为100000000000000.0。您无法从UserDefaults加载它。因此,即使存储了fastestScore,也不会在启动时加载它。

您应该通过两次更改来解决此问题。首先,在您的应用程序委托中,您应该注册默认的高分:

let bestScoreKey = "bestScore"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, willFinishLaunchingWithOptions options: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {
        UserDefaults.standard.register(defaults: [
            bestScoreKey: 1_000_000_000.0
        ])
        return true
    }

}

您还应该在那里注册任何其他默认设置。

其次,在ThirdViewController中,您应该从fastestScore初始化UserDefaults。您还可以将更改保存回属性UserDefaults观察员中的didSet

    var fastestScore: Double = UserDefaults.standard.double(forKey: bestScoreKey) {
        didSet {
            UserDefaults.standard.set(fastestScore, forKey: bestScoreKey)
        }
    }

其他提示:

  • 如果您的分数为fastestScore,则没有理由让Float成为Double。只需将其另存为Double

  • 不要重复字符串键。编译器不会捕获您的拼写错误。像往常使用bestScoreKey一样将密钥置于常量。

  • 您可以使用长数_来提高其可读性。

  • 侮辱你的播放器是一个值得怀疑的营销策略。如果您对问题的第一个评论是“认真的?”,您会有什么感受?你还在尝试吗?“