什么时候/如何排序Realm孩子 Swift中UITableView的属性

问题描述 投票:0回答:1

我在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个回答
1
投票

不,你不能在创建rowDates对象时对SectionDate成员进行排序。 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中制作数据的静态副本,但我认为除非遇到任何特定问题,否则不需要这样做。

© www.soinside.com 2019 - 2024. All rights reserved.