[英]Swift 4 What is the best way to store an array of custom types persistently?
我有一个数组,其中包含每个对象都具有自定义和非原始类型属性,如 URL 和 StorageReference (Firebase)。 持久存储此数组内容的最佳方法是什么? 我想过使用 Realm,但 Realm 只存储具有原始类型属性的对象。 随着应用程序的使用越来越多,从持久存储中检索的对象数量将继续增加,因为将从 Firebase 检索的项目越来越多。
Realm 支持以下属性类型: Bool 、 Int 、 Int8 、 Int16 、 Int32 、 Int64 、 Double 、 Float 、 String 、 Date 和 Data。
因此,理想情况下,您应该能够通过将任何自定义类型转换为合适的原始类型来覆盖它们。 例如,您可以在保存到 Realm 时将URL
保存为String
,并在检索时转换回来。
如果您不想包含第三方框架,您可以使用 Codable 协议并使用 NSKeyedArchiver 保存内容。 https://developer.apple.com/documentation/foundation/nskeyedarchiver
简单的例子:
struct A: Codable {
var myString: String? // primitive types are already codable
}
struct B: Codable {
var myInt: Int?
var a: A? // custom types need to be Codable
}
// save
let myObject = B()
NSKeyedArchiver.archiveRootObject(myObject, toFile: "/path/to/archive")
// load
let myObject = NSKeyedUnarchiver.unarchiveObjectWithFile("/path/to/archive") as? B
如果您的自定义类型更复杂,您可能希望实现自定义编码/解码方法以更好地控制数据的保存和加载方式。 https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.