我正在尝试提取属于最新Actions
的所有Session
。
在SQL中,这将是一个简单的JOIN ... WHERE Session.startTime = MAX(Session.startTime),但是使用Core Data我无法弄清楚如何在不采取以下两个步骤的情况下执行此操作。有什么想法吗?
// Step 1. Get the latest session
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:self.managedObjectContext]];
[request setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"startTime" ascending:NO]]];
[request setFetchLimit:1];
Session *lastSession = nil;
NSArray *objects = [self.managedObjectContext executeFetchRequest:request error:NULL];
if ([objects count] > 0)
{
NSLog(@"max: %@", [objects objectAtIndex:0]);
lastSession = [objects objectAtIndex:0];
}
// Step 2. Get that session's actions
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Action" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sectionSort = [[NSSortDescriptor alloc] initWithKey:@"session.startTime" ascending:NO selector:nil];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"startTime" ascending:NO selector:nil];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sectionSort, sort, nil]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"session.startTime = %@", lastSession.startTime];
//**Can't I do something like this instead?**
//NSPredicate *predicate = [NSPredicate predicateWithFormat:@"session.startTime = session.@max.startTime"];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchBatchSize:10];
[self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"session.startTime" cacheName:@"ActionHistory"];
self.fetchedResultsController.delegate = self;
NSError *error;
if (![self.fetchedResultsController performFetch:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort(); // Fail
}
编辑:我确实需要坚持使用上面没有详细说明的NSFetchedResultsController
正当理由。
答案 0 :(得分:0)
我建议你与Session
和Action
建立关系。
然后,在您获取所需的会话后,您可以将所有会话的操作视为简单的lastSession.actions
。
修改强> 也许你可以做到
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"session = %@",lastSession];