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

时间:2015-07-03 07:06:05

标签: ios xcode swift core-data nsuserdefaults

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

我可以显示结果,但无法保存。请帮忙! 此外,我希望如果我在问题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 个答案:

答案 0 :(得分:3)

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

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