如何使用NSCoding保存数据

时间:2016-02-16 02:55:41

标签: ios swift nscoding

我得到了Score.swift和ScoreManager.swift。

我的Score.swift看起来像这样:

class Score: NSObject, NSCoding {

let score:Int;
let dateOfScore:NSDate;

init(score:Int, dateOfScore:NSDate) {
    self.score = score;
    self.dateOfScore = dateOfScore;
}

required init(coder: NSCoder) {
    self.score = coder.decodeObjectForKey("score") as! Int;
    self.dateOfScore = coder.decodeObjectForKey("dateOfScore") as! NSDate;
    super.init()
}

func encodeWithCoder(coder: NSCoder) {
    coder.encodeObject(self.score, forKey: "score")
    coder.encodeObject(self.dateOfScore, forKey: "dateOfScore")
}
}

我的ScoreManager.swift看起来像这样:

class ScoreManager {
var scores:Array<Score> = [];

init() {
    // load existing high scores or set up an empty array
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    let path = documentsPath.stringByAppendingPathComponent("Scores.plist")
    let fileManager = NSFileManager.defaultManager()

    // check if file exists
    if !fileManager.fileExistsAtPath(path) {
        // create an empty file if it doesn't exist
        if let bundle = NSBundle.mainBundle().pathForResource("Scores", ofType: "plist") {
            do {
                try fileManager.copyItemAtPath(bundle, toPath: path)
            } catch {

            }
        }
    }

    if let rawData = NSData(contentsOfFile: path) {
        // do we get serialized data back from the attempted path?
        // if so, unarchive it into an AnyObject, and then convert to an array of Scores, if possible
        let scoreArray: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(rawData);
        self.scores = scoreArray as? [Score] ?? [];
    }
}

func save() {
    // find the save directory our app has permission to use, and save the serialized version of self.scores - the Scores array.
    let saveData = NSKeyedArchiver.archivedDataWithRootObject(self.scores);
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray;
    let documentsDirectory = paths.objectAtIndex(0) as! NSString;
    let path = documentsDirectory.stringByAppendingPathComponent("Scores.plist");

    saveData.writeToFile(path, atomically: true);
}

// a simple function to add a new high score, to be called from your game logic
// note that this doesn't sort or filter the scores in any way

func addNewScore(newScore:Int) {
    let newScore = Score(score: newScore, dateOfScore: NSDate());
    self.scores.append(newScore);
    self.save();
}
}

我的问题是: 如何调用这些NSCoding来保存实际gameView场景中的数据?

1 个答案:

答案 0 :(得分:0)

我强烈建议您阅读一本书或至少有关iOS编程的教程。但这是它的低点。

class ViewController: UIViewController {
    let scoreManager = ScoreManager()

    // Save the score to file. Hook it up to a button or label in your view
    @IBAction func save (sender: AnyObject) {
        scoreManager.save()
    }
}

如果您不知道如何将按钮/标签与@IBAction相关联,请在Google上找到相关教程。