iOS: Two Entities - Fetch, Merge, and Sort

会有一股神秘感。 提交于 2020-01-06 02:26:27

问题


I need to perform a fetch from two different entities, merge them, and then sort them based on a field that both entities have: 'lastModifiedDate'. lastModifiedDate is NSDate

NSFetchRequest *fetchRequest1 = [[NSFetchRequest alloc] init];
NSFetchRequest *fetchRequest2 = [[NSFetchRequest alloc] init];

NSEntityDescription *entity1 = [NSEntityDescription entityForName:@"Entity1" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest1 setEntity:entity1];

NSEntityDescription *entity2 = [NSEntityDescription entityForName:@"Entity2" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest2 setEntity:entity2];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastModeifiedDate" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

[fetchRequest1 setSortDescriptors:sortDescriptors];
[fetchRequest2 setSortDescriptors:sortDescriptors];

[self.managedObjectContext executeFetchRequest:fetchRequest onSuccess:^(NSArray *results) {
    [self.refreshControl endRefreshing];
    self.objects = results; //objects is an array @property
    [self.tableView reloadData];

} onFailure:^(NSError *error) {

    [self.refreshControl endRefreshing];
    NSLog(@"An error %@, %@", error, [error userInfo]);
}

I'm stuck here. I need to merge fetchRequest1 and fetchRequest2, and have the objects display in a tableViewController in descending order. Thanks.


回答1:


You can not merge two fetch requests, but you could merge and sort the fetched arrays:

NSArray *results1 = ...; // from first fetch request;
NSArray *results2 = ...; // from second fetch request;
NSMutableArray *merged = [[NSMutableArray alloc] init];
[merged addObjectsFromArray:results1];
[merged addObjectsFromArray:results2];
[merged sortUsingDescriptors:@[sortDescriptor]];

Alternatively, you could define an entity "Entity", make that the parent entity for "Entity1" and "Entity2", and define all common properties (such as "lastModifiedDate") in the parent entity. Then you can fetch and sort "Entity" objects.

(A possible disadvantage of entity inheritance is that Core Data uses a single table for all "Entity", "Entity1" and "Entity2" objects. This is not optimal if there are many properties that are not common to both.)



来源:https://stackoverflow.com/questions/17994961/ios-two-entities-fetch-merge-and-sort

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