我在两个实体之间有一对多实体关系:
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
我使用fetchresults控制器来显示结果。下面是fetch results控制器的实现:
#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
但是,这种方法不是这样的。我得到的行在正确的顺序,但部分没有秩序!我希望SortDescriptorUpdate在做他的工作。我错过了什么?在期待中感谢。