我将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 {
}
每次保存新的
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
}