已在 JSON 文件中保存数据,但无法检索以前的数据,只能检索新条目

Saved data on JSON file but can not retrieve previous data, only new entries

我将数据保存在第一个 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)
              }

      }

}

您需要在保存之前在此处加载数据...您还需要单独的 class 来保存和加载数据..在控制器中执行此操作..这违反了单一职责原则...您的加载函数应该 return [游戏] 数组,保存数据应该 return 成功或失败

@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()
    }