如何在Codable(Swift)中保存多个数据

时间:2018-06-29 07:06:15

标签: arrays swift data-structures codable

我将Codable协议与JSONEncoder和JSONDecoder一起使用。

但是当我保存数据时,只保存了最后一个值,但是我需要保存多个。

如果我添加三张卡,我只能看到最后一张。

示例:

我添加卡:

        CName: Test1, BarCode: 12345, CardNBR: 12345

        CName: Test2, BarCode: 1234567, CardNBR: 1234567

        CName: Test3, BarCode: 123456789, CardNBR: 123456789

最后我只能看到: CName:Test3,条形码:123456789,CardNBR:123456789

如何保存多个数据?

struct Entity : Codable  {

   var cname: String
   var barcode: String
   var cardnbr: String
}

保存

let arr = Entity(cname: CompanyName, barcode: BarCodeField, cardnbr: CardNumber)

do {
   let data  = try JSONEncoder().encode(all)
   UserDefaults.standard.set(data, forKey: "Key")
} catch {
   print(error)
}

加载

do {
   let content = UserDefaults.standard.data(forKey: "Key")
   let saved = try JSONDecoder().decode([Entity].self, from: content!)
   print(saved)
} catch {
   print(error)
}

let arr = Entity(cname: CompanyName, barcode: BarCodeField, cardnbr: CardNumber)

        let jsonEncoder = JSONEncoder()
        do {
            var jsonData = try jsonEncoder.encode(arr)
            let jsonString = String(data: jsonData, encoding: .utf8)
            print("JSON String : " + jsonString!)

            let jsonDecoder = JSONDecoder()
            let upMovie = try jsonDecoder.decode(Entity.self, from: jsonData)
            print("upMovie : \(upMovie)")
            print("cname : \(arr.cname)")
            print("barcode : \(arr.barcode)")
            print("cardnbr : \(arr.cardnbr)")
            entities.append(Entity(cname: arr.cname, barcode: arr.barcode, cardnbr: arr.cardnbr))
            print(entities)
        }
        catch {
        }

1 个答案:

答案 0 :(得分:2)

每次保存新

let arr = Entity(cname: CompanyName, barcode: BarCodeField, cardnbr: CardNumber)

仅包含一个实体,这就是您仅获取最后一个实体的原因

解决方案:保存之前,还必须添加最后保存的数组。
假设实体

let aEntity = Entity(CName: "Test1", BarCode: "12345", CardNBR: "12345")

并保存

if var all :[Entity] = loadData() {
    all.append(aEntity)
    saveData(allData: all)
}else {
    saveData(allData: [aEntity])
}

在课程中添加以下功能

func saveData(allData:[Entity]) {
    do {
        let data  = try JSONEncoder().encode(allData)
        UserDefaults.standard.set(data, forKey: "Key")
    } catch {
        print(error)
    }
}
func loadData() -> [Entity]?{
    do {
        if let content = UserDefaults.standard.data(forKey: "Key") {
            let saved :[Entity] = try JSONDecoder().decode([Entity].self, from: content)
            print(saved)
            return saved
        }
    } catch {
        print(error)
    }
    return nil
}