【问题标题】:When/How to sort Realm child <List> properties for UITableView in Swift何时/如何在 Swift 中对 UITableView 的 Realm 子 <List> 属性进行排序
【发布时间】:2019-03-10 20:08:04
【问题描述】:

我在 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 对象的初始化时执行此操作吗?

【问题讨论】:

    标签: swift uitableview realm


    【解决方案1】:

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

    您需要在对象的每个查询中对 rowDates 对象进行排序。一个建议是向SectionDate 类(已计算- 未存储)添加一个计算属性,该属性返回按要求排序的查询。然后在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 中制作数据的静态副本,但我认为没有必要这样做,除非您遇到任何特定问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多