1

Here I won't have any connection for both the pages and here I need to save the model class globally and to use anywhere in all pages till app was in use and after it may can clear the data having in array but I can able to access anywhere in all pages in app and I tried using to save in UserDefaults it crashed. Can anyone help me how to implement this?

var sortModel = [Sort]()

for (_, value) in sortJson as! [String: Any] { 
    self.sortModel.append(Sort.init(dict: value as! [String : Any]))
}
UserDefaults.standard.set(self.sortModel, forKey: "sorts")
rmaddy
  • 314,917
  • 42
  • 532
  • 579
User
  • 73
  • 1
  • 8
  • " I tried using to save in userdefaults it got crashed" Any error message? There is no `UserDefaults` line of code showed. In order to save `Sort` which is a Custom object into UserDefaults, you need to make it compliant with `NSCopy`, or since it seem you use JSON, Sort needs to be compliant with `Codable` and `Decodable` and you can save JSON in `UserDefaults` instead. – Larme Mar 16 '18 at 13:22
  • please provide the code. and do you need to persist data when app is relaunched? – Lead Developer Mar 16 '18 at 13:25
  • Its better to keep it at application level, if you dont want it to persist once app is closed. – Niki Mar 16 '18 at 13:25
  • this is the error `Attempt to insert non-property list object` and user defaults code added as shown above then how to make `NSCopy` and to save it in user defaults @Larme – User Mar 16 '18 at 13:34
  • yes I need as u told @hkg328 – User Mar 16 '18 at 13:35
  • Sorry, I meant `NSCoding` compliant, not `NSCopy`. Just do a quick search. – Larme Mar 16 '18 at 13:35

1 Answers1

0

Get your Sort struct to conform to Codable like:

struct Sort: Codable {
    //...
}

then you can quickly get away with:

//Encode Sort to json data
if let jsonData = try? JSONEncoder().encode(sortModel) {
    print("To Save:", jsonData)

    //Save as data
    UserDefaults.standard.set(jsonData,
                              forKey: "sorts")
}

//Read data for "sorts" key and decode to array of "Sort" structs
if let data = UserDefaults.standard.data(forKey: "sorts"),
    let sorts = try? JSONDecoder().decode([Sort].self,
                                          from: data) {
    print("Retrieved:", sorts)
}

Basically, we make a json out of the array and save it as a data object.
We then can get it back as data and recreate the sort struct array.

NOTE: This may not work if the struct has nested within itself some types that prevent it from getting encoded as a json.

In this case, read:

staticVoidMan
  • 19,275
  • 6
  • 69
  • 98