解码 RealmSwift 类中的可选对象列表



我正在尝试初始化 Realm 类中的对象编码列表,问题是当服务器返回空列表时应用程序崩溃

这是初始化列表的代码

class TicketDetails: Object, Decodable {
    var working: [WorkingHour]?
    var workingHours = List<WorkingHour>()
    public convenience required init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let workingArray = try container.decodeIfPresent(Array<WorkingHour>.self, forKey: .working) {
            working = workingArray
            workingHours.append(objectsIn: workingArray)
        } else {
            working = nil
            workingHours = List.init()
        }
    }
}

这里有一些奇怪之处。

TicketDetails被声明为 Realm 对象,但包含一个数组,该数组只是 Realm List 属性的副本。为什么?删除阵列。List 需要是一个 let,并删除整个 else 子句,因为这不起作用。

class TicketDetails: Object, Decodable 
{
  let workingHours = List<WorkingHour>()
  public convenience required init(from decoder: Decoder) throws {
    self.init()
    let container = try decoder.container(keyedBy: CodingKeys.self)
    if let workingArray = try container.decodeIfPresent(Array<WorkingHour>.self, forKey: .working) 
    {
        workingHours.append(objectsIn: workingArray)
    }
  }
}

最新版本的 RealmCocoa 4.4.1 中,它更方便、更有效。不要忘记定义 CodingKeys 枚举,如果网络响应与您的模型不同。

class TicketDetails: Object, Decodable {
    var working = List<[WorkingHour]>()
    var workingHours = List<WorkingHour>()
    public convenience required init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.working = try container.decodeIfPresent(List<WorkingHour>.self, forKey: .working) ?? List<WorkingHour>.self
        self.workingHours = try container.decodeIfPresent(List<WorkingHour>.self, forKey: .working) ?? List<WorkingHour>.self
    }
}

相关内容

  • 没有找到相关文章

最新更新