0

Session에 속하는 모든 Actions을 찾으려고합니다.NSFetchRequest, 집계 함수로 필터링 할 수 있습니까?

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 = [email protected]"]; 
[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

희망이 도움이 : [http://stackoverflow.com/questions/6515167/using-min-max-and-etc-inside-a -predicate] [1] [1] : http://stackoverflow.com/questions/6515167/using-min-max-and-etc-inside-a-predicate 배열을위한 필터링 –

+0

그래도 가져 오기 요청을 필터링하고 싶습니다. – trapper

답변

0

SessionAction 사이의 관계를 설정하는 것이 좋습니다. 그런 다음 필요한 세션을 가져온 후에는 해당 세션의 모든 작업을 easy ss lastSession.actions으로 가져올 수 있습니다.

편집 아마 당신이 할 수있는

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"session = %@",lastSession]; 
+0

나는이 두 가지 사이에 이미 관계가있다. 하지만 그런 식으로 더 이상 NSFetchedResultsController's'의 모든 이점을 사용할 수는 없었습니다. – trapper

+0

내 대답을 업데이트했습니다. –

+0

하지만 그 술어를 사용할 수 있으려면 먼저 lastSession을 별도로 가져와야합니다. – trapper

관련 문제