我想知道是否有任何特殊的方法如何在 SwiftData 持久存储中存储 Data 类型的变量。我记录中的所有数据都存储良好,但数据类型却不然。我的模型是这样定义的
@Model
final class Purchase {
@Attribute(.unique) var purchaseID: String
var item: String
var comment: String?
var documentURL: URL?
var bookmarkURL: Data?
var purchaseDate: Date
var endOfWarranty: Date
var rating: Double
.....
}
然后在我的代码中我像这样存储(更新现有记录)
purchase?.shop = selectedShop
purchase?.item = item
purchase?.comment = comment
purchase?.documentURL = documentURL
purchase?.bookmarkURL = bookmarkURL
purchase?.purchaseDate = date
purchase?.endOfWarranty = Calendar.current.date(byAdding: .month, value: warranty, to: date)!
do {
try modelContext.save()
} catch let error {
isError = true
errMsg = error.localizedDescription
}
purchase.bookmarkURL 保持 null/nil,即使 bookmarkURL 变量已填充。 感谢您的提示。
我见过的存储
Data
属性的解决方案是,应该使用 @Attribute(.externalStorage)
将其存储在外部文件中
@Attribute(.externalStorage) var bookmarkURL: Data?