我正在制作游戏,我想使用设置单例类。我从互联网上获得了这个代码示例。但是加载这个类有问题。无法理解如何在保存后加载这些属性。
class Settings: NSObject, NSCoding {
static let DocumentDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentDirectory.appendingPathComponent("settings")
static let shared = Settings()
var level: Int = 1
var moves: Int = 0
var music: Bool = true
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
level = aDecoder.decodeInteger(forKey: SNames.CurrentLevelSName)
music = aDecoder.decodeBool(forKey: SNames.MusicSName)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(level, forKey: SNames.CurrentLevelSName)
aCoder.encode(music, forKey: SNames.MusicSName)
}
func loadGame() -> Settings? {
return NSKeyedUnarchiver.unarchiveObject(withFile: Settings.ArchiveURL.path) as? Settings
}
func save() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(self, toFile: Settings.ArchiveURL.path)
if !isSuccessfulSave {
print("Failed to save Settings...")
}
}
}
答案 0 :(得分:1)
如果要获取设置,则必须执行操作,然后才能访问级别,移动和其他属性。这是一些代码。
if let settings = Settings.shared.loadGame() {
print(settings.level)
}
这将加载设置并打印关卡。