skip to Main Content

I am trying to archive data and want to store it in userdefault but app getting crash.

enter image description here

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


  1. As mentioned in the comments to use NSKeyedArchiver the class must adopt NSSecureCoding and implement the two required methods.

    The types in your class are JSON compatible, so adopt Codable and archive the data with JSONEncoder (or PropertyListEncoder). You could even use a struct and delete the init method

    struct SelectedProductDetail: Codable {
    
        let product: String
        var amount: Double
        var title: String
    }
    
    var productDetails = [String: SelectedProductDetail]()
    // populate the dictionary 
    
    do {
        let data = try JSONEncoder().encode(productDetails)
        UserDefaults.standard.set(data, forKey: "productDetails")
    } catch {
        print(error)
    }
    

    And load it

    do {
        guard let data = UserDefaults.standard.data(forKey: "productDetails") else { return }
        productDetails = try JSONDecoder().decode([String: SelectedProductDetail].self, from: data)
    } catch {
        print(error)
    }
    

    Note:

    UserDefaults is the wrong place for user data. It’s better to save the data in the Documents folder

    Login or Signup to reply.
  2. For this case you can use UserDefaults

    struct ProductDetail: Codable {
        //...
    }
    
    let encoder = JSONEncoder()
    
    let selectedProductDetails = ProductDetail()
    
    // Set
    if let data = try? encoder.encode(selectedProductDetails) {
        UserDefaults.standard.set(data, forKey: "selectedProductDetails")
    }
    
    // Get
    if let selectedProductDetailsData = UserDefaults.standard.object(forKey: "selectedProductDetails") as? Data {
        let selectedProductDetails = try? JSONDecoder().decode(ProductDetail.self, from: selectedProductDetailsData)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search