我有两个模型(“类别”模型和“项目”模型),如下所示。“类别”通过属性“项目”与“项目”有多方面的关系。
我想得到按“订单”排序的“类别”和“项目”的数据,但我怎么做呢?
我只能根据“类别”的顺序对“类别”进行排序,但不能用“项目”来排序。
let categories = realm.objects(Category.self).sorted(byKeyPath: "order", ascending: true)

发布于 2020-07-22 15:06:05
你真的离得不远。
领域结果对象可以是无序的,因此有一个策略来保持结果对象按所需的顺序加载是很重要的。实际上,您已经在类别对象中使用了
@objc dynamic var order: Int = 0 // use this for sorting另一方面,领域列表对象保持其插入顺序。
class Category: Object {
let items = List<Item>因此,如果将鸡肉添加到类别项目列表中,然后是猪肉,则该顺序将保持不变;鸡肉位于索引0,猪肉位于索引1。
Meat
chicken
pork这是在领域文档中涵盖的
保证列表属性保留其插入顺序。
因此,在填充tableView时,可以使用tableView titleForHeaderInSection从结果对象获取节名(类别:肉类、蔬菜、水果)(因为在从领域加载结果时对它们进行了排序)。
然后,对于每个部分中的行,您可以读取项目的分类->项列表,因为它们在列表中,所以它们将通过插入来排序。
为了完整起见,下面是处理tableView部分的代码
//
//handle sections
//
func numberOfSections(in tableView: UITableView) -> Int {
return self.yourCategoryResults.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let title = self.yourCategoryResults[section].name //the section title
return title
}然后是处理每个节中的行的代码。
//
//handleTableView rows
//
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rowsInSection = self.yourCategoryResults[section].items.count
return rowsInSection
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier", for: indexPath)
let item = self.yourCategoryResults[indexPath.section].items[indexPath.row]
let text = item.name
cell.textLabel?.text = text
return cell
}https://stackoverflow.com/questions/62967502
复制相似问题