How to sort Core Data results based on an attribute of related object collection?

♀尐吖头ヾ 提交于 2019-12-05 07:40:45

You could add an attribute in ObjectB which is the time stamp of the add date, then in the fetch request you can do something like this:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"objectB.addTime" ascending:YES];
...
fetchRequest.sortDescriptors = @[descriptor];

I know this question is a bit old but what I did was get all ObjectBs, iterate over the results and pull out the ObjectB property and add it to a new array.

NSFetchRequest *fetchRequest = [NSFetchRequest new];
[fetchRequest setEntity:self.entityDescForObjectB];

// sort
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
[fetchRequest setSortDescriptors:@[sortDescriptor]];

NSError *error = nil;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    NSLog(@"Error fetching objects: %@", error.localizedDescription);
    return;
}

// pull out all the ObjectA objects
NSMutableArray *tmp = [@[] mutableCopy];
for (ObjectB *obj in fetchedObjects) {
    if ([tmp containsObject:obj.objectA]) {
        continue;
    }
    [tmp addObject:obj.objectA];
}

This works because CoreData is an object graph so you can work backwards. The loop at the end basically checks to see if the tmp array already has a specific ObjectA instance and if not adds it to the array.

It's important that you sort the ObjectBs otherwise this exercise is pointless.

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