2011-10-24 40 views
3

我有一個UITableView它使用2 NSFetchedResultsControllers。每個NSFetchedResultsController只有一個部分。但是,該表格有4個部分。我使用NSFetchedResultsControllers之一的結果填充表格的第4部分。到目前爲止一切正常。但是,如果用戶刪除第一部分中的第一個單元格,則更改NSFetchedResultsControllers。表格最後一部分的行可能會被刪除。當這種方法被稱爲:多個NSFetchedResultsController - didChangeObject

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
    atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type 
    newIndexPath:(NSIndexPath *)newIndexPath 
{ 
UITableView *tableView = self.tableView; 

switch(type) { 
    case NSFetchedResultsChangeInsert: 
     [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     break; 

    case NSFetchedResultsChangeDelete: 
     NSLog(@"section: %d, row: %d", [newIndexPath section], [newIndexPath row]); 

     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     break; 
... 
} 

的部分始終爲0,因爲它是NSFetchedResultsControllers的部分。因此,該部分與表格視圖中的正確部分不匹配。

是否有解決方法?我基本上想要將NSFetchedResultsController的部分更改爲3而不是0.

回答

2

我找到了一個解決方法,但是如果有一個更漂亮的解決方案將會很不錯。

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
    atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type 
    newIndexPath:(NSIndexPath *)newIndexPath 
{ 
UITableView *tableView = self.tableView; 
if (newIndexPath != nil && controller == self.fetchedXController) { 
    newIndexPath = [NSIndexPath indexPathForRow:[newIndexPath row] inSection:3]; 
    if ([tableView cellForRowAtIndexPath:newIndexPath] == nil) { 
     type = NSFetchedResultsChangeInsert; 
    } 
} 
if (indexPath != nil && controller == self.fetchedDomainsController) { 
    indexPath = [NSIndexPath indexPathForRow:[indexPath row] inSection:3]; 
} 

switch(type) { 
    case NSFetchedResultsChangeInsert: 
     [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     break; 

    case NSFetchedResultsChangeDelete: 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     break; 

    case NSFetchedResultsChangeUpdate: 
     [self configureCell:[tableView cellForRowAtIndexPath:newIndexPath] atIndexPath:newIndexPath]; 
     break; 
... 
相關問題