2つのエンティティ間に1対多のエンティティ関係があります。
EntityP (Parent) <-->> EntityC (Child)
属性と関係:
EntityP.title
EntityP.dateTimeStamp
EntityP.PtoC (relationship)
EntityC.title
EntityC.dateTimeStamp
EntityC.CtoP (relationship) // Can be used to get "one" EntityP record
結果を表示するためにフェッチ結果コントローラーを使用します。フェッチ結果コントローラーの実装は次のとおりです。
#pragma mark -
#pragma mark Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController {
// Set up the fetched results controller if needed
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
// Create the fetch request for the entity
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Set Entity
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityC" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set Predicate
// (Ignore, we want to get list of all EntityC records)
// Set Sort Descriptors (sort on Parent - for section, and then on Child - for rows)
NSSortDescriptor *sortDescriptorPDate = [[NSSortDescriptor alloc] initWithKey:@"CtoP.dateTimeStamp" ascending:YES];
NSSortDescriptor *sortDescriptorDate = [[NSSortDescriptor alloc] initWithKey:@"dateTimeStamp" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorPDate, sortDescriptorDate, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:20];
// Create and initialize the fetch results controller
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"CtoP.title" cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
// Cleanup memory
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptorPDate release];
[sortDescriptorDate release];
[sortDescriptors release];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return fetchedResultsController;
}
たとえば、永続ストアに次のデータがある場合:
EntityP.dateTimeStamp EntityP.title EntityC.dateTimeStamp EntityC.title
Today B Today d
Yesterday A Yesterday a
Today B Yesterday c
Yesterday A Today b
注:昨日と今日はNSDate形式です。
次に、セクションと行を次の順序で(正確に)取得する必要があります。
A
a
b
B
c
d
しかし、ソートはこのようには機能しません。行は正しい順序で取得されていますが、セクションは順序付けられていません。sortDescriptorPDateが彼の仕事をしていることを願っています。私は何が欠けていますか?期待して感謝します。