When/How 为 Swift 中的 UITableView 排序 Realm 子 <List> 属性

When/How to sort Realm child <List> properties for UITableView in Swift

我在 UITableView 中使用 2 个 Realm 对象作为数据源:

class SectionDate: Object {

   @objc dynamic var date = Date()
   let rowDates = List<RowDate>() 
}
class RowDate: Object {

   @objc dynamic var dateAndTime = Date()
}
tableViewData = realm.objects(SectionDate.self).sorted(byKeyPath: "date", ascending: isAscending)

func numberOfSections(in tableView: UITableView) -> Int {
    return tableViewData.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return tableViewData[section].rowDates.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    ...
    cell.rowDate = tableViewData[indexPath.section].rowDates[indexPath.row]
    ...
}

我将如何订购 section.rowDate ,何时订购?

看起来我无法将其作为 section.sorted(byKeyPath) 查询的一部分来完成...我会在 SectionDate 对象的初始化时完成吗?

不,您不能在创建 SectionDate 对象时对 rowDates 成员进行排序。 List 是一种不(必须)以排序方式存储列表的领域类型。

您需要在每次查询对象时对 rowDates 个对象进行排序。一个建议是将计算的 属性 添加到 SectionDate class(计算的 - 未存储的),返回按要求排序的查询。然后在 cellForRowAt 函数中访问 属性。例如:

extension SectionDates
{
  var sortedRowDates
  {
    return rowDates.sorted(byKeyPath: "date", ascending: isAscending)
  }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  ...
  cell.rowDate = tableViewData[indexPath.section].sortedRowDates[indexPath.row]
  ...
}

这当然意味着每个单元格的查询都是 运行,但这没关系。还有其他解决方案,例如在 viewDidLoad 中制作数据的静态副本,但我认为没有必要这样做,除非您 运行 遇到任何特定问题。