ios - NSFetchRequest/NSFetchedResultsController 返回不同的单个属性,但使用实体的另一个属性进行排序

标签 ios nsfetchedresultscontroller nsfetchrequest

我正在使用 NSFetchedResultsController 在表中显示数据。数据存储包含许多具有 groupID 的行,并且多个实体可以共享一个 groupID

每个实体也有一个插入日期属性。

我想获取按插入日期属性排序的不同groupID 列表。以下代码有效,但它不按插入日期属性排序。我认为由于该属性不是正在获取的属性之一,因此它不可用于排序。

我也在使用 MagicalRecord,fwiw。

有没有办法使用实体的其他属性进行排序,但不将它们作为结果的一部分?将插入日期添加到获取的属性中显然是多余的,因为日期都是唯一的。

     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userID like[c] %@", THEUSERUSERID];

     NSFetchRequest *fetchRequest = [AnEntity MR_requestAllWithPredicate:predicate];
     [fetchRequest setReturnsDistinctResults:YES];
     [fetchRequest setResultType:NSDictionaryResultType];
     [fetchRequest setPropertiesToFetch:@[@"groupID"]];

     NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"inDate" ascending:NO];

     [fetchRequest setSortDescriptors:@[sortDescriptor]];

     _frController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[NSManagedObjectContext MR_rootSavingContext] sectionNameKeyPath:nil cacheName:nil];

最佳答案

Chadbag ...我遇到了同样的问题。我研究了 setPropertiesToFetch,发现它需要 NSPropertyDescriptions 的 NSArray ...而不仅仅是属性名称。

我想如果你删除这个:

[fetchRequest setPropertiesToFetch:@[@"groupID"]];

并添加:

NSDictionary *entityProperties = [entity propertiesByName];
NSPropertyDescription *propDescription = [entityProperties objectForKey:@"groupID"];
NSArray *propArray = [NSArray arrayWithObject:propDescription];
[fetchRequest setPropertiesToFetch:propArray];

这应该对你有用......它对我有用!

关于ios - NSFetchRequest/NSFetchedResultsController 返回不同的单个属性,但使用实体的另一个属性进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20754047/

相关文章:

ios - 每个人的Facebook应用测试

ios - 在 Swift 4 中从计算变量创建关键路径

iphone - NSFetchedResultsController sectionIndexTitles 错误不是英文字母

ios - 从核心数据中删除对象并切换 View Controller 时崩溃

javascript - TitaniumStudio 不更新新文件

ios - swift : Value Changing Control Events Not Calling?

cocoa - NSFetchedResultsController 缓存再次不匹配

ios - Objective-C 中按一个属性对自定义对象的 NSSet 进行排序

ios - executeFetchRequest 挂起,从不返回错误或继续

iphone - iOS:在运行时以编程方式添加自定义字体