从plist文件保存和加载数字

时间:2018-03-05 23:44:46

标签: ios swift plist

我正在尝试从游戏中的plist中保存并加载当前级别。

这就是我的plist的样子:

enter image description here

这是我现在加载和保存数据的代码:

class SavedLevel: NSObject, NSCoding {
 var level: Double

 required init(level:Double = 1) {
    self.level = level
 }

 required init?(coder aDecoder: NSCoder) {
    self.level = aDecoder.decodeObject(forKey: "Level") as? Double ?? 0
 }

 func encode(with aCoder: NSCoder) {
    aCoder.encode(level, forKey: "Level")
 }
}
class DataModel: NSObject {

 var saveLevels = SavedLevel()

 func documentsDirectory()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths.first!
    return documentsDirectory
 }

 func dataFilePath()->String {
    return self.documentsDirectory().appendingFormat("/CurrentLevel.plist")
 }

 override init() {
    super.init()
    print("document file: \(documentsDirectory())")
    print("data file: \(dataFilePath())")
 }

 func saveData() {
        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWith: data)
        archiver.encode(saveLevels, forKey: "CurrentLevel")
        archiver.finishEncoding()
        data.write(toFile: dataFilePath(), atomically: true)
 }

 func loadData() {
        let path = self.dataFilePath()
        let defaultManager = FileManager()
        if defaultManager.fileExists(atPath: path) {
            let url = URL(fileURLWithPath: path)
            let data = try! Data(contentsOf: url)
            let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
            saveLevels = unarchiver.decodeObject(forKey: "CurrentLevel") as! SavedLevel
            unarchiver.finishDecoding()
        }
 }
}

以下是我如何增加关卡数量以及如何尝试保存播放器的当前关卡:

var currentLevelNum = 1

if score >= level.targetScore {
        gameOverPanel.image = UIImage(named: "LevelComplete")
        currentLevelNum = Int(dataModel.saveLevels.level)
        if currentLevelNum < NumLevels {
            currentLevelNum += 1
            dataModel.saveLevels.level = Double(currentLevelNum)
        }
        dataModel.saveData()
        print("Updated level: ",dataModel.saveLevels.level)
        showGameOver()
    } else if movesLeft == 0 {
        gameOverPanel.image = UIImage(named: "GameOver")
        dataModel.saveData()
        showGameOver()
    }

以下是我尝试将数据保存在AppDelegate文件中的方法(省略了不必要的代码):

class AppDelegate {

   var dataModel = DataModel()

   func applicationDidEnterBackground(_ application: UIApplication) {
       saveData()
       print("Level when app was sent to background: ",dataModel.saveLevels.level)
   }

   func applicationWillTerminate(_ application: UIApplication) {
       saveData()
       print("Level when app was terminated: ",dataModel.saveLevels.level)

   }

   func saveData() {
       dataModel.saveData()
   }

当级别完成并且增加1时,SavedLevel中的级别变量正在更新。但是当我将应用程序发送到后台时,将打印plist中Level的原始值。

示例:

Level at startup:  0.0
Updated level:  1.0
Updated level:  2.0
Level when app was sent to background:  1.0
Updated level:  3.0
Level when app was sent to background:  1.0

与保存关卡有关的工作不正常,我无法弄清问题是什么。

感谢任何指导!

1 个答案:

答案 0 :(得分:0)

使用此:

var myDict: NSDictionary?
if let path = Bundle.main.path(forResource: "Info", ofType: "plist") {
    myDict = NSDictionary(contentsOfFile: path)
    let level = myDict?.object(forKey: "level") as! String
    print("Your level is: \(level)")
}