我正在尝试学习Swift,并且在存储自定义类的数组时遇到困难。这是我的课程
import Foundation
class Entry {
var company: String
var category: String
var amount: Double
var type: String
init() {
self.company = ""
self.category= ""
self.amount= ""
self.type= ""
}
}
我还有另一个类,它是一组称为支票簿的条目
import Foundation
class Checkbook {
var entries = [Entry]()
init() {
self.entries = []
}
}
然后在我的视图控制器中,我有一系列的支票簿。我需要存储该数组的支票簿,以便下次应用程序打开时保留所有数据。最好的方法是什么?
答案 0 :(得分:2)
您可以使用Codable协议将类编码和解码为JSON文件,但我建议使用结构:
struct Entry: Codable {
let company, category, type: String
let amount: Double
}
struct CheckBook: Codable {
var entries: [Entry] = []
}
extension FileManager {
static let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
游乐场测试:
let checkBooks: [CheckBook] = [.init(entries: [.init(company: "ACME", category: "JSON", type: "Swift", amount: 5.0)])]
do {
let destinationURL = FileManager.documentDirectory.appendingPathComponent("CheckBooks.json")
try JSONEncoder().encode(checkBooks).write(to: destinationURL)
print("json encoded/saved")
let loadedCheckBooks = try JSONDecoder().decode([CheckBook].self, from: .init(contentsOf: destinationURL))
print(loadedCheckBooks) // CheckBook(entries: [Entry(company: "ACME", category: "JSON", type: "Swift", amount: 5.0)])\n"
} catch {
print(error)
}