-1

I want to save a struct which can not be modified to UserDefaults in my code. I went through a number of solutions but everyone is advising to use Codable/NSCoding in the struct. I can not edit the struct. Does anyone have an idea how we can achieve this.

I tried to wrap the object to an NSDictionary but while trying to save, it crashes saying 'Attempt to insert non-property list object'. Is it because I have nil values in my model?

Any help is appreciated.

Daniyar
  • 2,975
  • 2
  • 26
  • 39
iOSManiac
  • 139
  • 1
  • 11
  • 3
    [edit] your question to include the `struct` definition. Why can't you add `Codable` conformance in an `extension`? – Dávid Pásztor May 22 '19 at 12:52
  • Event if this structure was defined in separate module you had no access you can extend it to be `Codable`. – Daniyar May 22 '19 at 13:30
  • @Astoria: It is giving me the error 'Implementation of 'Decodable' cannot be automatically synthesized in an extension in a different file to the type' and Implementation of 'Encodable' cannot be automatically synthesized in an extension in a different file to the type. Do you have any solution for this? – iOSManiac May 23 '19 at 07:43
  • @iOSManiac implement the protocol methods yourself – Daniyar May 23 '19 at 07:53

2 Answers2

2

If you can't change your struct, then create an extension for it and conform it to Codable.

Once conformed to Codable, you can use JSONEncoder and JSONDecoder to convert to and from data and then save/retrieve from UserDefaults.

struct Sample {
    var name = "Sample Struct"
}

extension Sample: Codable {

}

let obj = Sample()
let data = try? JSONEncoder().encode(obj)

//Saving in UserDefaults
UserDefaults.standard.set(data, forKey: "SampleStruct")

//Fetching from UserDefaults
if let data = UserDefaults.standard.data(forKey: "SampleStruct") {
    let val = try? JSONDecoder().decode(Sample.self, from: data)
    print(val) //Sample(name: "Sample Struct")
}
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • Since it is in a different file I am getting error like 'Implementation of 'Decodable' cannot be automatically synthesized in an extension in a different file to the type' and Implementation of 'Encodable' cannot be automatically synthesized in an extension in a different file to the type. – iOSManiac May 23 '19 at 08:29
0

I tried to wrap the object to an NSDictionary

You can't save a custom model without conforming to Codable/NSCoding , if you don't need to conform then save it as a usual Array/Dictionary without wrapping any custom objects inside

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87