我有一个基于关卡的游戏,我需要跟踪两个属性,即使应用程序关闭后:立方精华,浮点数和高分,字典([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对象并在每个级别存档一个新的。所以它会是这样的:
这是一个很好的方法吗?每次玩家通过关卡时,存档和取消存档都会导致性能过重吗?