I am trying to archive data and want to store it in userdefault but app getting crash.
Also tried this
let encodedData = try NSKeyedArchiver.archivedData(withRootObject: selectedPoductDetails, requiringSecureCoding: false)
selectedPoductDetails is dict of type [String: SelectedProductDetail]
import Foundation
class SelectedProductDetail {
let product: String
var amount: Double
var title: String
init(product: String, amount: Double, title: String ) {
self.product = product
self.amount = amount
self.title = title
}
}
May i know why its not working and possible solution for same?
2
Answers
As mentioned in the comments to use
NSKeyedArchiver
the class must adoptNSSecureCoding
and implement the two required methods.The types in your class are JSON compatible, so adopt
Codable
and archive the data withJSONEncoder
(orPropertyListEncoder
). You could even use a struct and delete theinit
methodAnd load it
Note:
UserDefaults
is the wrong place for user data. It’s better to save the data in theDocuments
folderFor this case you can use UserDefaults