我多久可以在Swift中归档和取消归档持久数据

我多久可以在Swift中归档和取消归档持久数据,swift,Swift,我有一个基于关卡的游戏,我需要跟踪两个属性,即使在应用程序关闭后也是如此:cube Essential、Float和high scores、dictionary([Int:Float])。这是我创建的类: class PlayerData: NSObject, NSCoding { // Properties var cubeEssence : Float var levelHighScore : [Int : Float] //Archiving Paths static let Docu

我有一个基于关卡的游戏,我需要跟踪两个属性,即使在应用程序关闭后也是如此:cube Essential、Float和high scores、dictionary([Int:Float])。这是我创建的类:

class PlayerData: NSObject, NSCoding {

// Properties
var cubeEssence : Float
var levelHighScore : [Int : Float]

//Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("data")

struct PropertyKey {
    static let essence = "essence"
    static let highScore = "highScore"
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(cubeEssence, forKey : PropertyKey.essence)
    aCoder.encode(levelHighScore, forKey : PropertyKey.highScore)
}

init?(cubeEssence: Float, levelHighScore: [Int : Float]) {
    self.cubeEssence = cubeEssence
    self.levelHighScore = levelHighScore
}

required convenience init?(coder aDecoder: NSCoder) {

    var cubeEssence : Float = 0
    if let essence = aDecoder.decodeObject(forKey: PropertyKey.essence) as? Float {
        cubeEssence = essence
    }

    var levelHighScore : [Int : Float] = [:]
    if let highScore = aDecoder.decodeObject(forKey: PropertyKey.highScore) as? [Int : Float] {
        levelHighScore = highScore
    }

    self.init(cubeEssence : cubeEssence, levelHighScore : levelHighScore)
}
}
我最初的计划很简单:在应用程序开始时加载PlayerData,并在应用程序终止时关闭它。然而,我已经读到,依赖applicationWillTerminate()方法并不是那么可靠。所以我在考虑取消归档旧的PlayerData对象,并在每个级别归档一个新的对象。所以它是这样的:

  • 播放器打开应用程序
  • PlayerData未归档并分配给变量
  • 玩家开始玩一个关卡,并获得一个新的高分或更多
  • 我取消归档PlayerData(如果有)并归档一个新的,其中包含更新的数据。这样做是为了始终只有一个PlayerData对象

  • 这是一个很好的方法吗?每次玩家通过一个关卡时,存档和取消存档的性能是否太高?

    我会说,为你的特定应用测试它,如果有任何性能问题,请进行优化。由于您正在存档的数据的大小,在一个应用程序中有效的内容可能在另一个应用程序中无效。@paulvs是否有其他方法来存档而不是使用NSCoding对象?有核心数据、plists、NSUserDefaults(不安全)、序列化为JSON文件、,等等。请参见此处了解核心数据与归档:@paulvs对于我试图评分的内容(浮点和字典),您最推荐的是什么?老实说,您不太可能在未归档/归档包含分数的对象(浮点和字典)时遇到问题。