iOS:两个实体-提取,合并和排序 [英] iOS: Two Entities - Fetch, Merge, and Sort

查看:79
本文介绍了iOS:两个实体-提取,合并和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从两个不同的实体中进行提取,合并,然后根据两个实体都具有的字段 lastModifiedDate对它们进行排序。 lastModifiedDate是NSDate

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]);
}

我被困在这里。我需要合并fetchRequest1和fetchRequest2,并以降序在tableViewController中显示对象。谢谢。

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

推荐答案

您不能合并两个获取请求,但是可以合并并排序获取的数组:

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]];

或者,您可以定义一个实体 Entity,使之成为父实体
作为 Entity1和 Entity2,并在父实体中定义所有公共属性(例如
lastModifiedDate)。然后,您可以获取实体对象并对其进行排序。

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.

(实体继承的一个可能的缺点是,Core Data对所有
Entity都使用一个表, Entity1和 Entity2对象。如果有很多
属性都不是两者的共同点,那么这不是最佳选择。)

(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.)

这篇关于iOS:两个实体-提取,合并和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆