0

Goal: is to save array data to be retrieved by next session

Approach: encode the array to Json, store in UserDefaults, then retrieve data and decode to the array. Maybe a better way, assume wrapping in Json is the best way to transport to UserDefaults

I think my encode and save to UserDefault works & I can return the object and print a size... don't know how to decode back to my array?

    var matrixArray =  [matrixItem]()
    var returnArray: Decodable = [returnMatrixItem]()

    let encoder = JSONEncoder()
    let decoder = JSONDecoder()

     @IBAction func restoreFrom(_ sender: Any) {
        let   restoredJson: Data = UserDefaults.standard.data(forKey: "storeArray")!

// its here that i can't determine how to decode the return value to my array
// error: cannot invoke decode with an argument list of type([Decodeable], from Data:)
        try! JSONDecoder().decode([returnArray.self], from: restoredJson)
        print("return json size \(restoredJson)")*

    }

    @IBAction func appendItem(_ sender: Any) {
     if let newValue = newItem.text  {
  print(newValue)
            newItem.text = "  "
     let    itemToAdd = matrixItem(matrixName: newValue, matrixDescription: itemDescription.text!)

         matrixArray.append(itemToAdd)
        print(matrixArray)
        let  jsonData = try! encoder.encode(matrixArray)
        print("Print json data \(jsonData)")
        UserDefaults.standard.set(jsonData, forKey: "storeArray")

        }

    }
Code Different
  • 90,614
  • 16
  • 144
  • 163
Jake
  • 39
  • 1
  • Here is a greate tutorial for encoding and decoding JSON in swift 4. https://www.raywenderlich.com/172145/encoding-decoding-and-serialization-in-swift-4 . Also I wouldn't not recomend to hold a lot of data in UserDefaults - it is going to store data in your phone memore. The app would slow down while running it. Use local data base. – yerpy Dec 21 '17 at 19:48
  • Supporting @yerpy‘s recommendation. Switched from user defaults to a local SQLite Database. More complex but with a good wrapper (I.e SQLite.Swift) a very fast data “storage” – Aeger Dec 23 '17 at 13:44

0 Answers0