iOS:对 NSFetchedResultsController 进行排序和分组

编程入门 行业动态 更新时间:2024-10-27 11:19:38
本文介绍了iOS:对 NSFetchedResultsController 进行排序和分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个具有以下结构的表

I have two tables with the following structure

主要类别:

name position hasSubCategories

子类别:

name position display belongsToMainCategory

现在我想显示按主类别分组的所有子类别(其中显示属性 = YES).主要类别部分应按位置定义排序,子类别本身(在部分内)按其位置属性进行排序.(顺便说一下,对于某个主要类别,名称可以相同……我的表具有更多属性,但它们与理解问题无关).但我的订单完全搞砸了.为什么?这是我的 FetchedResultsController 代码:

Now I want to display all subcategories (where display attribute = YES) grouped by main category. The main category sections should be sorted as defined by position and the subcategories itself (within the section) by their position attribute. (name by the way can be the same for a certain main category...my tables have more attributes but they aren't relevant to understand the problem). But my order is completely messed up. Why? Here's my code for the FetchedResultsController:

NSError *error = nil; NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"]; NSSortDescriptor *mainCatPosition = [[NSSortDescriptor alloc] initWithKey:@"belongsToMainCategory.position" ascending:YES]; NSSortDescriptor *subCatPosition = [[NSSortDescriptor alloc] initWithKey:@"position" ascending:YES]; request.sortDescriptors = [NSArray arrayWithObjects:mainCatPosition,subCatPosition,nil]; request.predicate = [NSPredicate predicateWithFormat:@"display = %@", [NSNumber numberWithBool:YES]]; [self.db.managedObjectContext executeFetchRequest:request error:&error]; self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:self.budgetDatabase.managedObjectContext sectionNameKeyPath:@"belongsToMainCategory.name" cacheName:nil];

推荐答案

用作 sectionNameKeyPath: 参数的关键路径到获取的结果控制器必须与第一个排序描述符中使用的键相同或生成相同的相对顺序.

The key path used as sectionNameKeyPath: argument to the fetched results controller must be the same key that is used in the first sort descriptor or generate the same relative ordering.

fetched results controller首先根据第一个对所有fetched对象进行排序对描述符进行排序,然后根据 sectionNameKeyPath 将对象分组.因此,使用不同的键路径(例如belongsToMainCategory.position"与belongsToMainCategory.name")不起作用.这甚至可能导致有关乱序部分"的运行时错误.

The fetched results controller first orders all fetched objects according to the first sort descriptor and then groups the objects into sections according to the sectionNameKeyPath. Therefore using different key paths (as in your case "belongsToMainCategory.position" vs. "belongsToMainCategory.name") does not work. This could even cause a runtime error about "out of order sections".

更多推荐

iOS:对 NSFetchedResultsController 进行排序和分组

本文发布于:2023-11-25 16:29:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630494.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:iOS   NSFetchedResultsController

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!