0

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

Gaurav Bharti
  • 1,065
  • 1
  • 14
  • 22

2 Answers2

0

Replace this code with your code then remove app and run again.

  required init(coder aDecoder: NSCoder) {           
     transOBJ = = aDecoder.decodeObject(forKey: "OBJ") as! [JSON]
 }
KKRocks
  • 8,222
  • 1
  • 18
  • 84
0

Thank you Tj3n. JSON also need to conform NSCoding. Just Transactions isn't enough. I created different variables for string and integers in the Transactions NSObject, extracted data from JSON, stored extracted data in the variables declared and then encoded and decoded them accordingly. It worked.

If there is another way, I'm all ears.

Gaurav Bharti
  • 1,065
  • 1
  • 14
  • 22