2014-12-07 78 views
0

我建立一個通用的FetchedResultsController DataSource類要在我所有的TableViewControllers使用,他們中的一些有多個部分,有些不是(像任何項目)。刪除最後一節排的泰伯維NSFetchedResultsController

問題是,當所取出的結果控制器有多個區段(sectionNameKeyPath不爲空)上didChangeObject刪除邏輯必須刪除整個部分,如果有對的TableView部分只有一行,但相同的邏輯沒有按如果在獲取結果控制器定義(sectionNameKeyPath = nil)上只設置了一個部分,則不起作用。

任何人都知道如何實現上didChangeObject通用刪除邏輯,以防止這種錯誤?

例外:

例外是從 NSFetchedResultsController的委託 通話-controllerDidChangeContent中捕獲:.無效的更新:無效的部分數量。包含在表視圖 後的部分的數量的更新(1)必須等於包含在 部分的數量的更新(1)前表視圖,加上或減去的插入或缺失的 區段0的數目(插入,1刪除)。與用戶信息 (空)

//Fetched Results Controller Definition on My Model Class 
+ (NSFetchedResultsController*)fetchedResultsController 
{ 
    NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:[self.class entityName]]; 

    //request.predicate = [NSPredicate predicateWithFormat:@"parent = %@", self]; 
    request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"dueDate" ascending:NO]]; 

    [request setFetchLimit:50]; 

    //Generate an error 
    return [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:Store.defaultManagedObjectContext sectionNameKeyPath:nil cacheName:nil]; 

    //Works Fine 
    //return [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:Store.defaultManagedObjectContext sectionNameKeyPath:@"shortDueDate" cacheName:nil]; 
} 


//Fetched Results Controller Generic Data Source Class 
- (void)controller:(NSFetchedResultsController*)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath*)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath*)newIndexPath 
{ 
    if (type == NSFetchedResultsChangeInsert) { 
     [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
    } else if (type == NSFetchedResultsChangeMove) { 
     [self.tableView moveRowAtIndexPath:indexPath toIndexPath:newIndexPath]; 
    } else if (type == NSFetchedResultsChangeDelete) { 

     BOOL deleteSection = FALSE; 

     //If have only one section and its the last row then delete entire section 
     if ((self.tableView.numberOfSections == 1) && ([self.tableView numberOfRowsInSection:[indexPath section]] == 1)) { 
      deleteSection = TRUE; 
     } 

     if (deleteSection) { 
      [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:YES]; 
     } else { 
      [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     } 
    } else { 
     NSAssert(NO,@""); 
    } 
} 
+0

究竟什麼是你的問題? – 2014-12-07 18:32:30

+1

對不起米爾茲,無意中貼出!現在是正確的。 – carantes 2014-12-07 19:45:18

回答

1

如果您實現:

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo 
     atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type 

那麼FRC將決定你的部分是否需要插入或刪除。