2013-05-09 26 views
2

我有現有的核心數據模型,有實體視頻。 我想更新一個應用程序,我想添加另一個實體到名爲Project的對象。 看來我使用核心數據燈遷移實現了這一點。NSFetchedResultsController來自多個實體和更新模型

現在我想視頻是項目的孩子。最後在UITableView中,我想將項目作爲節標題和視頻顯示爲行。

什麼是最好的方法來實現它? 目前我正在使用NSFetchedResultsController查詢核心數據。 謝謝

回答

2

如果我沒有弄錯,可以使用輕量級遷移實現這種更改。您必須在項目實體和視頻實體之間創建一對多的有序關係。您仍然可以使用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]; 
... 
}