gpt4 book ai didi

ios - Realm 中 NSData 的可选列表 - Swift

转载 作者:行者123 更新时间:2023-11-29 05:09:08 24 4
gpt4 key购买 nike

我需要将图像列表保存为 Realm 中的 NSData。我尝试使用 Realm 可选,但是 realmOptional<NSdata>无法使用,因为 realmOptional不符合 NSDate 类型。
有办法做到吗?

编辑:基本上我想要的就是能够存储 NSData 列表但可选像这样:

@objc dynamic var photos: List<NSData>?

最佳答案

使用 Decodable 时可选列表类型的解决方案

就我而言,我需要一个可选的List,因为我正在将 json 解码为 Realm 对象,并且该属性可能不存在于 json 数据中。典型的解决方法是手动解码并使用 decodeIfPresent()。这并不理想,因为它需要模型中的样板代码:

class Driver: Object, Decodable {
var vehicles = List<Vehicle>()
var name: String = ""
// etc

public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.vehicles = try container.decodeIfPresent(List<Vehicle>.self, forKey: .vehicles) ?? List<Vehicle>()
self.name = try container.decode(String.self, forKey: .name)
// etc
}
}

但是,我们可以通过使用 List 类型的重载扩展 KeyedDecodingContainer 来避免样板文件。这将强制使用 decodeIfPresent() 解码所有列表:

  • Realm v5:

    class Driver: Object, Decodable {
    var vehicles = List<Vehicle>()
    var name: String = ""
    //etc
    }

    class Vehicle: Object, Decodable {
    var drivers = List<Driver>()
    var make: String = ""
    // etc
    }

    extension KeyedDecodingContainer {
    // This will be called when any List<> is decoded
    func decode<T: Decodable>(_ type: List<T>.Type, forKey key: Key) throws -> List<T> {
    // Use decode if present, falling back to an empty list
    try decodeIfPresent(type, forKey: key) ?? List<T>()
    }
    }
  • Realm v10+:

    class Driver: Object, Decodable {
    @Persisted var vehicles: List<Vehicle>
    @Persisted var name: String = ""
    // etc
    }

    class Vehicle: Object, Decodable {
    @Persisted var drivers: List<Driver>
    @Persisted var make: String = ""
    // etc
    }

    extension KeyedDecodingContainer {
    // This will be called when any @Persisted List<> is decoded
    func decode<T: Decodable>(_ type: Persisted<List<T>>.Type, forKey key: Key) throws -> Persisted<List<T>> {
    // Use decode if present, falling back to an empty list
    try decodeIfPresent(type, forKey: key) ?? Persisted<List<T>>(wrappedValue: List<T>())
    }
    }

编辑:澄清代码示例,修复拼写错误

关于ios - Realm 中 NSData 的可选列表 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59848871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com