xcode swift:NSUserDefaults:如果退出应用程序,则保存高分并在停止的地方重新启动它

Posted

技术标签:

【中文标题】xcode swift:NSUserDefaults:如果退出应用程序,则保存高分并在停止的地方重新启动它【英文标题】:xcode swift: NSUserDefaults : save the highscore if quit app and restart it where left off 【发布时间】:2015-07-03 07:06:04 【问题描述】:

我正在制作一个测验应用程序。所以基本上我有分数和高分,我想在主视图控制器上显示和存储结果。

我可以显示结果,但无法保存。请帮忙! 另外我希望如果我在问题 2 中退出我的应用程序,它将从那里重新启动,而不是 isInitialViewController。 对于这两个主题的任何帮助将不胜感激。

以下是加载分数的主配置文件的代码,但一旦您退出应用并重新加载,数字就会消失:

import UIKit
import Parse
import ParseUI
import CoreData
import Foundation

class UserProfileViewController: UIViewController 

    @IBOutlet var scoreLabelUser: UILabel!
    var scoringString = String()

    @IBOutlet var HighScoreLabelUser: UILabel!
    var highscoreString = String()

    @IBOutlet var HighScoreLabel: UILabel!
    var HighscoreInt = 0

    override func viewDidLoad() 
        super.viewDidLoad()

        var highScoreDefault2 = NSUserDefaults.standardUserDefaults()
        if (highScoreDefault2.valueForKey("EASYHIGHSCORE") != nil)
        
        HighscoreInt = highScoreDefault2.valueForKey("EASYHIGHSCORE") as! NSInteger
            //highscoreString = highScoreDefault2.valueForKey("EASYHIGHSCORE") as! String
            HighScoreLabel.text = NSString(format: "%i", HighscoreInt) as String

        

        assignScores()

    



    func assignScores() 

        scoreLabelUser.text = NSString(format: "%@", scoringString) as String
        HighScoreLabelUser.text = NSString(format: "%@", highscoreString) as String
        HighScoreLabel.text = "\(highscoreString)"

        var highScoreDefault2 = NSUserDefaults.standardUserDefaults()
        highScoreDefault2.setValue(HighscoreInt, forKey: "EASYHIGHSCORE")

    


我有第二个 ViewController,它实际上有测验并且正在计算分数和高分。

//
//  EasyQuizViewController.swift
//  Quiz

    import UIKit
    import CoreData
    import AVFoundation

    class EasyQuizViewController: UIViewController 

        @IBOutlet var sequence: UILabel!

        @IBOutlet var questionLabel: UILabel!

        @IBOutlet var Button1: UIButton!
        @IBOutlet var Button2: UIButton!
        @IBOutlet var Button3: UIButton!
        @IBOutlet var Button4: UIButton!

        @IBOutlet var scoreLabel: UILabel!
        @IBOutlet var highscoreLabel: UILabel!

        var CorrectAnswer = String()
        var questionNumber = 0

        var score = 0
        var highScore = 0


        override func viewDidLoad() 
            super.viewDidLoad()

            var highScoreDefault = NSUserDefaults.standardUserDefaults()

            if (highScoreDefault.valueForKey("HIGHSCORE") != nil)
            
            highScore = highScoreDefault.valueForKey("HIGHSCORE") as! NSInteger!
            highscoreLabel.text = NSString(format: "%i", highScore) as String
            
            generateNewNumber()

            // Do any additional setup after loading the view.
        


        func generateNewNumber() 

            questionNumber += 1

            switch(questionNumber) 

            case 1:

                sequence.text = "\(questionNumber)/50"
                questionLabel.text = "Which is the country with the most people?"
                Button1.setTitle("United States of America", forState: UIControlState.Normal)
                Button2.setTitle("South Africa", forState: UIControlState.Normal)
                Button3.setTitle("China", forState: UIControlState.Normal)
                Button4.setTitle("India", forState: UIControlState.Normal)

                CorrectAnswer = "3"

                break

            case 2:

                sequence.text = "\(questionNumber)/50"
                questionLabel.text = "Which is the planet closest to the Sun?"
                Button1.setTitle("Venus", forState: UIControlState.Normal)
                Button2.setTitle("Jupiter", forState: UIControlState.Normal)
                Button3.setTitle("Earth", forState: UIControlState.Normal)
                Button4.setTitle("Mercury", forState: UIControlState.Normal)

                CorrectAnswer = "4"

                break


            default:

                var alert = UIAlertView(title: "Finished", message: "Your quiz has been completed. Click Okay to view scores.", delegate: self, cancelButtonTitle: "Ok")

                alert.show()

                //println("\(score)")
                //println("\(highScore)")

                scoreLabel.text = NSString(format: "%i", score) as String

                if (score > highScore) 
                    highScore = score

                highscoreLabel.text = NSString(format: "%i", highScore) as String
                


                var highScoreDefault = NSUserDefaults.standardUserDefaults()

                highScoreDefault.setValue(highScore, forKey: "HIGHSCORE")






                self.profileScreen()


            break

            

        




        @IBAction func Button1Action(sender: AnyObject) 

            if (CorrectAnswer == "1")
            

                score += 1
                generateNewNumber()
            
            else 

                generateNewNumber()
            
        

        @IBAction func Button2Action(sender: AnyObject) 

            if (CorrectAnswer == "2")
            

                score += 1
                generateNewNumber()
            
            else 

                generateNewNumber()
            
        

        @IBAction func Button3Action(sender: AnyObject) 

            if (CorrectAnswer == "3")
            

                score += 1
                generateNewNumber()
            
            else 

                generateNewNumber()
            
        

        @IBAction func Button4Action(sender: AnyObject) 

            if (CorrectAnswer == "4")
            

                score += 1
                generateNewNumber()
            
            else 

                generateNewNumber()
            
        


        @IBAction func BackBtn(sender: AnyObject) 
            self.performSegueWithIdentifier("backToProfile", sender: self)
        

        func profileScreen() 
            self.performSegueWithIdentifier("backToProfile", sender: self)
        


        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 
            var destinationViewController : UserProfileViewController = segue.destinationViewController as! UserProfileViewController


            //println("\(scoreLabel)")
            //println("\(highscoreLabel)")

            destinationViewController.scoringString = NSString(format: "%i", score) as String
            destinationViewController.highscoreString = NSString(format: "%i", highScore) as String
            //destinationViewController.HighscoreInt = NSString(format: "%i", highScore) as String
            //destinationViewController.HighscoreInt = (highScore) as NSInteger


        


    

【问题讨论】:

【参考方案1】:

您应该在用户退出您的应用时存储您的 NSUserDefaults:

func applicationDidEnterBackground(application: UIApplication) 
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.synchronize()

【讨论】:

谢谢。重新启动应用程序时,它仍然没有加载保存的值。 尝试使用:highScoreDefault2.synchronize() after highScoreDefault2.setValue(HighscoreInt, forKey: "EASYHIGHSCORE") 我试过了,但它也不起作用。如果我应该做其他事情,你有什么建议吗?你能快速看一下我的代码吗?谢谢

以上是关于xcode swift:NSUserDefaults:如果退出应用程序,则保存高分并在停止的地方重新启动它的主要内容,如果未能解决你的问题,请参考以下文章

NSUserDefault 同步后退按钮 swift

Swift 问题 - NSUserDefault 和 Settings Bundle 没有响应

NSUserDefault 无法在 iOS8 的扩展中保存和加载

我如何访问 iOS 项目的 NSUserDefault 以做出原生反应?

将分数发布到 Game Center 排行榜

NsMutable 不是 swift 中 [anyobject] 的子类型