在JSON文件中保存了数据,但不能检索以前的数据,只能检索新的条目。

问题描述 投票:0回答:1

我将数据保存在第一个VC的JSON文件中,在切换标签时也加载数据并显示。当我杀死程序或重新运行程序,在JSON文件中添加新的数据时,只有那些新的数据在JSON文件中,以前的数据已经消失了(没有手动删除),无法加载。我如何保存文件,以便下次运行程序时,它将只是追加到以前的数据?

class ViewController: UIViewController {

var game : Game?
var weekLeague : [[Game]]? = []

override func viewDidLoad() {
        super.viewDidLoad()
        creation()
}

@IBAction func endWLButton(_ sender: UIButton) {
        if games != nil {
            weekLeague?.append(games!)
        }

        save()
    }

func save(){
        guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
        let fileUrl = documentDirectoryUrl.appendingPathComponent("ArrayOfArray.json")
        print(fileUrl)
        let json = try? JSONEncoder().encode(weekLeague)

        do {
            try json?.write(to: fileUrl)
                print(json!)
            print(weekLeague)

             print("JSON data was written to teh file successfully!")
        }catch{
            print(error)
        }
    }

   func ShouldSendGame(game: Game) {
    self.game = game
    games?.append(game)
}

 func creation(){
        let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!

        let jsonFilePath = documentsDirectoryPath.appendingPathComponent("ArrayOfArray.json")
        let fileManager = FileManager.default
        var isDirectory: ObjCBool = false

        // creating a .json file in the Documents folder
        if !fileManager.fileExists(atPath: jsonFilePath!.path, isDirectory: &isDirectory) {
            let created = fileManager.createFile(atPath: jsonFilePath!.path, contents: nil, attributes: nil)
            if created {
                print("File created ")
            } else {
                print("Couldn't create file for some reason")
            }
        } else {
            print("File already exists")
        }
    }


}



class AllLeagueController : UITableViewController {
    var arrayOfArrayGamesCopy : [[Game]] = []

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
         DispatchQueue.global().async {
            self.loadData()
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }

    }


 func loadData() {
         guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
            let fileUrl = documentsDirectoryUrl.appendingPathComponent("ArrayOfArray.json")

              do{
                  let data = try Data(contentsOf:fileUrl)
                  let decoder = JSONDecoder()
                  let jsonData = try decoder.decode([[Game]].self, from: data)
                   arrayOfArrayGamesCopy = jsonData
                    print("Succes")
                print(jsonData.count)
              } catch{
                  print(error)
              }

      }

}
json swift persistence
1个回答
1
投票

你需要在这里加载数据,然后再保存... 另外,你需要有单独的类来保存和加载数据......点在控制器中做......它违反了单一责任原则......你的加载函数应该返回[游戏]的数组,保存数据应该返回成功或失败的结果

@IBAction func endWLButton(_ sender: UIButton) {
    //load and set data in games from file ...then append current data and save to file 
        if games != nil {
            weekLeague?.append(games!)
        }

        save()
    }
© www.soinside.com 2019 - 2024. All rights reserved.