最近的搜索结果加入了Core Data

时间:2009-05-16 21:11:48

标签: iphone core-data

这是关于核心数据的saving recent searches上一篇文章的后续问题。

为了对搜索结果进行分组,我有一个Entry实体和History实体。 Entry.history是与历史的关系。 History.entries是Entry的一个to-many关系(Entry.history的反转)。历史记录具有日期属性createdAt。我试图找出如何在NSFetchedResultsController中获取属于最新History实体的所有Entry实体。

我可以像这样获得最近的历史实体

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"History" inManagedObjectContext:context];
    [request setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];
    [request setFetchLimit:1];
    NSArray *results = [context executeFetchRequest:request error:&error];
    History *history = (History *)[results objectAtIndex:0];

然后NSFetchedResultsController中的Entry实体就像这样

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"history == %@", history];
    request = [[NSFetchRequest alloc] init];
    entity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:context];
    [request setEntity:entity];
    [request setPredicate:predicate];
    fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:@"Root"];

但我想在一个请求中执行此操作。请注意我只关心存储Entry结果的fetchedResultsController。

1 个答案:

答案 0 :(得分:1)

您应该能够拥有一个遵循关系的排序描述符:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entry" 
                                          inManagedObjectContext:context];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
                                    initWithKey:@"history.createdAt"
                                      ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor
                                                      count:1];
[request setEntity:entity];
[request setSortDescriptors:sortDescriptors];
[request setFetchLimit:1];
fetchedResultsController = [[NSFetchedResultsController alloc]
                            initWithFetchRequest:request
                            managedObjectContext:context 
                              sectionNameKeyPath:nil 
                                       cacheName:@"Root"];