我在努力挽救我比赛的高分。我正试图通过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中遇到了一个错误,说“expected declaration”,我不知道如何正确地实现它。
或者我应该用NSArchiver来做这个?如果是这样的话,我怎么能实现呢?

最佳答案

使用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)

        }
    }

关于swift - 使用NSUserDefaults保存高分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25985450/

10-13 03:24