使用NSUserDefaults保存高分

时间:2014-09-23 01:22:13

标签: swift nsuserdefaults

我试图保存游戏的高分。我试图通过NSUserDefaults来做这件事。这是我使用的代码:

//To save highest score
var highestScore:Int = 20
NSUserDefaults.standardUserDefaults().setObject(highestScore, forKey:"HighestScore")
NSUserDefaults.standardUserDefaults().synchronize()

//To get the saved score
var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("HighestScore") as Int
println(savedScore)

但我收到错误,NSUserDefaults说"预期声明"我无法弄清楚如何正确实现这一点。 或者我应该使用NSArchiver吗?如果是这样的话我怎么能实现呢?

1 个答案:

答案 0 :(得分:3)

使用NSCoding。创建一个Swift文件“HighScore”

import Foundation

class HighScore: NSObject {

    var highScore: Int = 0

    func encodeWithCoder(aCoder: NSCoder!) {
           aCoder.encodeInteger(highScore, forKey: "highScore")
    }

    init(coder aDecoder: NSCoder!) {
        highScore = aDecoder.decodeIntegerForKey("highScore")
    }

    override init() {
    }
}

class SaveHighScore:NSObject {

    var documentDirectories:NSArray = []
    var documentDirectory:String = ""
    var path:String = ""

    func ArchiveHighScore(#highScore: HighScore) {
        documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        documentDirectory = documentDirectories.objectAtIndex(0) as String
        path = documentDirectory.stringByAppendingPathComponent("highScore.archive")

        if NSKeyedArchiver.archiveRootObject(highScore, toFile: path) {
            println("Success writing to file!")
        } else {
            println("Unable to write to file!")
        }
    }

    func RetrieveHighScore() -> NSObject {
        var dataToRetrieve = HighScore()
        documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        documentDirectory = documentDirectories.objectAtIndex(0) as String
        path = documentDirectory.stringByAppendingPathComponent("highScore.archive")
        if let dataToRetrieve2 = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HighScore {
            dataToRetrieve = dataToRetrieve2
        }
        return(dataToRetrieve)
    }
}

然后是你的ViewController:

   import UIKit


    class ViewController: UIViewController, UITextFieldDelegate {
        var Score = HighScore()

        override func viewDidLoad() {
            super.viewDidLoad()

        Score.highScore = 100
        SaveHighScore().ArchiveHighScore(highScore: Score)
        var retrievedHighScore = SaveHighScore().RetrieveHighScore() as HighScore
        println(retrievedHighScore.highScore)

        }
    }