0

我正在尝试拉出所有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上面未详细说明的正当理由。

4

1 回答 1

0

我会建议你建立关系 beetwenSessionAction. 然后,在您获取所需的会话之后,您可以轻松地获取该会话的所有操作 ss lastSession.actions

编辑 也许你可以做

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"session = %@",lastSession];
于 2012-05-25T09:22:30.233 回答