2010-10-03 124 views
0

的更改我對核心數據的常規使用模式非常熟悉,但最近偶然發現了一個問題:想象一下,我有一個人的實體,有2個字符串屬性名稱和公司的簡單案例。我想讓UITableView按名稱排序並按公司名稱劃分。聽起來很簡單:核心數據:對

... 
personFetchController_ = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                  managedObjectContext:mainDataCenter.managedObjectContext 
                   sectionNameKeyPath:@"company" 
                     cacheName:@"PersonListCache"];  
NSError *error = nil; 
if (![personFetchController_ performFetch:&error]) 
{ 
    LogError(@"Error fetching persons: %@", [error localizedDescription]); 
} 
personFetchController_.delegate = self; 

我註冊不如授人以聽變化,特別是更改爲部分:

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo 
      atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type 
{ 
    NSIndexSet *sections = [NSIndexSet indexSetWithIndex:sectionIndex]; 
    switch (type) 
    { 
     case NSFetchedResultsChangeInsert: 
      [personTableView_ insertSections:sections withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
     case NSFetchedResultsChangeDelete: 
      [personTableView_ deleteSections:sections withRowAnimation:UITableViewRowAnimationFade]; 
     default: 
      break; 
    } 
} 

它非常好,當我添加/刪除/改變一個人的名字,但如果我更改了一個人的公司名稱(意思是從一個部分移動到另一個部分),應用程序崩潰,在插入後說,部分中的行數需要是舊值加1。

任何人都有這個工作權利?

回答

0

導致此崩潰的代碼最有可能不是此方法。

請張貼此方法的代碼:

-(void)controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: 

尤其是你如何用一種NSFetchedResultsChangeMove的變化做出反應?

在蘋果的文檔NSFetchedResultsControllerDelegate他們用這個didChangeObject

:...

case NSFetchedResultsChangeMove: 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
        withRowAnimation:UITableViewRowAnimationFade]; 
     [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] 
        withRowAnimation:UITableViewRowAnimationFade]; 
     break; 

之前,我發現了蘋果的文檔包含了幾乎所有必要的代碼NSFetchedResultsController我使用了一些代碼,從網絡,我想從一些教程,這在罕見的事件中導致崩潰。過了一段時間後,我發現在將第一部分中的唯一對象(將被刪除)移動到第二部分(這將是新的第一部分)時,我可以觸發此操作。

從此我在閱讀教程之前先閱讀並搜索Apple-Documentation ^^