I'm trying to store a custom class in user defaults but throughs an exception
terminating with uncaught exception of type NSException
My class is as follows: Transactions
import Foundation
import SwiftyJSON
class Transactions: NSObject,NSCoding {
var transOBJ = [JSON]()
init(transOBJ:[JSON]) {
self.transOBJ = transOBJ
}
required convenience init(coder aDecoder:NSCoder) {
let obj = aDecoder.decodeObject(forKey: "OBJ") as! [JSON]
self.init(transOBJ: obj)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(transOBJ, forKey: "OBJ")
}
}
The exception is throwing on aCoder.encode(transOBJ, forKey: "OBJ")
The code for saving in user defaults is:
let trans = [Transactions(transOBJ: self.transactionObjs)]
var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: trans)
userDefaults.set(encodedData, forKey: "transactions")
userDefaults.synchronize()
Update 1
I am calling the user defaults inside the Alamofire request function. Then it is giving an error But when I call it outside Alamofire request function, then it runs just fine. What should I do? I want to save it inside the success of alamofire but can't do it