Core Data一对多排序

Core Data one-to-many sorting

我有 CoreData 对象 "Entity" 和 @property (nonatomic, retain) NSSet *ImagesSet;

ImagesSet 内部有许多 "ImageEntity" 个对象。

"ImageEntity"有@property (nonatomic, retain) NSNumber * sortKey;

如何使用按 sortKey 字段排序的图像集为 "Entity" 创建 fetchRequest?

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity"
                                          inManagedObjectContext:[[DataManager sharedInstance] mainObjectContext]];
[fetchRequest setEntity:entity];
NSString * predicate = some predicate string......;
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:predicate]];
[fetchRequest setFetchBatchSize:2500];
[fetchRequest setFetchLimit:25];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"ImageEntity.sortKey" ascending:NO];

NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

NSFetchedResultsController *frc = nil;

 frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                          managedObjectContext:mainObjectContext
                                            sectionNameKeyPath:nil
                                                     cacheName:cashName];

程序崩溃并显示消息“***** 由于未捕获的异常 'NSInvalidArgumentException',正在终止应用程序,原因:'to-many key not allowed here'**”

当您提取 Entity 个对象时,无法控制相关 ImageEntity 个对象的顺序 作为提取的一部分 。您有几个选择:

  1. 在您的数据模型中指定关系是有序的。该关系将表示为 NSOrderedSet 而不是 NSSet。您必须确保根据需要订购该套装(而不是使用 sortKey)。

  2. 保持关系无序 (NSSet),并在需要时对集合进行排序。例如

    NSSortDescriptor *imageSort = [NSSortDescriptor sortDescriptorWithKey:@"sortKey" ascending:NO];
    NSArray *sortedImages = [myEntity.imagesSet sortedArrayUsingDescriptors:@[imageSort]];
    
  3. 直接获取ImageEntity对象,使用谓词将结果过滤到相关Entity对象,以及所需的排序描述符:

    NSSortDescriptor *imageSort = [NSSortDescriptor sortDescriptorWithKey:@"sortKey" ascending:NO];
    NSFetchRequest *imageFetch = [NSFetchRequest fetchRequestWithEntityName:@"ImageEntity"];
    imageFetch.sortDescriptors = @[imageSort];
    imageFetch.predicate = [NSPredicate predicateWithFormat:@"entity == %@",myEntity];
    NSError *error;
    NSArray *sortedImages = [context executeFetchRequest:imageFetch error:&error];