Core Data one-to-many sorting

限于喜欢 提交于 2019-12-04 13:41:42

When you fetch Entity objects, there is no way to control the order of the related ImageEntity objects as part of the fetch. You have a few options instead:

  1. Specify in your data model that the relationship is ordered. The relationship will be represented as NSOrderedSet instead of NSSet. You will have to ensure that the set is ordered as you need (instead of using sortKey).

  2. Keep the relationship as unordered (NSSet), and sort the set when you need to. Eg.

    NSSortDescriptor *imageSort = [NSSortDescriptor sortDescriptorWithKey:@"sortKey" ascending:NO];
    NSArray *sortedImages = [myEntity.imagesSet sortedArrayUsingDescriptors:@[imageSort]];
    
  3. Fetch the ImageEntity objects directly, using a predicate to filter the results to the relevant Entity object, and the required sort descriptor:

    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];
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!