如果我沒有弄錯,可以使用輕量級遷移實現這種更改。您必須在項目實體和視頻實體之間創建一對多的有序關係。您仍然可以使用NSFetchedResultsController獲取項目列表,然後遍歷與Video實體的關係以獲取關聯的對象。它看起來或多或少是這樣的:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext: context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setRelationshipKeyPathsForPrefetching: @"videos"];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
initWithFetchRequest: fetchRequest
managedObjectContext: context
sectionNameKeyPath: nil
cacheName: nil];
我們正在建立一個NSFetchRequest對象預取的「視頻」的關係訪問視頻的實體時,這將節省一些時間。然後,檢索項目實體的名單後,您就可以訪問他們的tableView:的cellForRowAtIndexPath:
- (NSInteger) numberOfSectionsInTableView: (UITableView*) tableView
{
return [self.fetchedResultsController.fetchedObjects count];
}
- (NSInteger) tableView: (UITablView*) tableView numberOfRowsInSection: (NSInteger) section
{
Project *project = [self.fetchedResultsController.fetchedObjects objectAtIndex: section];
return [project.videos count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
Project *project = [self.fetchedResultsController.fetchedObjects objectAtIndex: indexPath.section];
Video *video = [project.videos objectAtIndex: indexPath.row];
...
}