0

Actions最新の に属するすべてを取得しようとしていSessionます。

SQL では、これは単純な JOIN ... WHERE Session.startTime = MAX(Session.startTime) になりますが、Core Data では、以下の 2 つの手順に頼らずにこれを行う方法を理解できません。何か案は?

// 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

と の間に関係を築くことをお勧めしSessionますAction。次に、必要なセッションをフェッチした後、そのセッションのすべてのアクションを簡単に ss として取得できますlastSession.actions

編集 できるかもしれません

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