一尘不染

如何在默认用户中保存对象列表?

swift

我的对象是:

 struct Order: Codable {
        var item_id:String = ""
        var quantity:Int = 0
        var image:String = ""
        var name:String = ""
        var desc:String = ""
    }

函数的类别是:

    class func saveOrder(value: [Order]) {
        print(value)
        let placesData = NSKeyedArchiver.archivedData(withRootObject: value)
        UserDefaults.standard.set(placesData, forKey: "orderHistoryArray")
    }

    class func getOrder() -> [Order] {
        if let order = UserDefaults.standard.array(forKey: "orderHistoryArray") {
            return order as! [Order]
        }
        return []
    }

当我尝试使用此功能时:

            SavedData.saveOrder(value: itemsInCart)

它不和我一起工作,有帮助吗?!!!


阅读 166

收藏
2020-07-07

共1个答案

一尘不染

我用这个类来解决这个问题:

class Order: NSObject, NSCoding {


var item_id:String = ""
var quantity:String = ""
var image:String = ""
var name:String = ""
var desc:String = ""

init(item_id: String ,quantity : String , image : String , name: String, desc: String){
    self.item_id = item_id
    self.quantity = quantity
    self.image = image
    self.name = name
    self.desc = desc
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(item_id, forKey: "item_id")
    aCoder.encode(quantity, forKey: "quantity")
    aCoder.encode(image, forKey: "image")
    aCoder.encode(name, forKey: "name")
    aCoder.encode(desc, forKey: "desc")
}

required init?(coder aDecoder: NSCoder) {
    self.item_id = aDecoder.decodeObject(forKey: "item_id") as! String
    self.quantity = aDecoder.decodeObject(forKey: "quantity") as! String
    self.image = aDecoder.decodeObject(forKey: "image") as! String
    self.name = aDecoder.decodeObject(forKey: "name") as! String
    self.desc = aDecoder.decodeObject(forKey: "desc") as! String
}
}

然后我用这个功能来使用它

class func save(value : Order){
    var orderArray:[Order] = retrive()
    orderArray.append(value)
    let orderArrayAchived = NSKeyedArchiver.archivedData(withRootObject: orderArray)
    UserDefaults.standard.set(orderArrayAchived, forKey: "orderArray")
}

class func saveListOfOrder(value: [Order]) {
    print(value)
    let cartArrayAchived = NSKeyedArchiver.archivedData(withRootObject: value)
    UserDefaults.standard.set(cartArrayAchived, forKey: "orderArray")
}

class func retrive()-> [Order]{
    let orderData = UserDefaults.standard.object(forKey: "orderArray") as? NSData
    if orderData == nil
    {
        return [Order]()
    }
    let orderArray = NSKeyedUnarchiver.unarchiveObject(with: orderData! as Data) as? [Order]
    return orderArray!
}
2020-07-07