2010-04-13 36 views
0

我很難用核心數據添加新項目到我的表格視圖。以下是我的代碼中的簡要邏輯。在我的ViewController類,我有一個按鈕,trigle編輯模式:將新項目添加到UITableView和核心數據作爲數據源?

- (void) toggleEditing { 
    UITableView *tv = (UITableView *)self.view; 
    if (isEdit) // class level flag for editing 
    { 
    self.newEntity = [NSEntityDescription insertNewObjectForEntityName:@"entity1" 
     inManagedObjectContext:managedObjectContext]; 
    NSArray *insertIndexPaths = [NSArray arrayWithObjects: 
     [NSInextPath indexPathForRow:0 inSection:0], nil]; // empty at beginning so hard code numbers here. 
    [tv insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade]; 
    [self.tableView setEditing:YES animated:YES]; // enable editing mode 
    } 
    else { ...} 
} 

在這段代碼塊,我說我現在的管理對象範圍內的新項目第一,然後我添加了一個新行我電視。我認爲,在我的數據源或環境,在我的表視圖的行數的對象都數應爲1

然而,我在TabView的的情況下,有一個例外:numberOfRowsInSection:

無效更新:第0節中的行數無效。更新(0)後現有節中包含的行數必須等於更新前該節中包含的行數(0),加上或減去數字從該部分插入或刪除的行(插入了1個,刪除了0個)。

唯一的例外是委託事件之後提出:

- (NSInteger) tableView:(UITableView *) tableView numberOfRawsInSection:(NSInteger) section { 
    // fetchedResultsController is class member var NSFetchedResultsController 
    id <NSFechedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] 
    objectAtIndex: section]; 
    NSInteger rows = [sectionInfo numberOfObjects]; 
    return rows; 
} 

在調試模式下,我發現,各行仍然0,後偶數toggleEditing的調用該事件。它看起來像從fetchedResultsController獲取的sectionInfo沒有包含插入的新實體對象。不知道我是否錯過任何東西或步驟?我不確定它是如何工作的:在新的實體插入當前的託管對象上下文時,讓fetcedResultsController通知或反映更改?

回答

0

我想我有一個解決方案。實際上,我不需要在toggleEditing事件中創建實體。然後在提交插入事件時創建實體對象。這是我在toggleEditing事件代碼更新:

- (void) toggleEditing { 
    UITableView *tv = (UITableView *)self.view; 
    if (isEdit) // class level flag for editing 
    { 
    insertRows = 1; // NSInteger value defined in the class or header 
    NSArray *insertIndexPaths = [NSArray arrayWithObjects: 
    [NSInextPath indexPathForRow:0 inSection:0], nil]; // empty at beginning so hard code numbers here. 
    [tv insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade]; 
    [self.tableView setEditing:YES animated:YES]; // enable editing mode 
    } 
    else { insertRows = 0; ...} 
} 

在活動現場,一排動態插入到當前表視圖。由於新的行被添加,在下面的委託,我必須確保在部分返回的行反映了煽動:

- (NSInteger) tableView:(UITableView *) tableView numberOfRawsInSection:(NSInteger) section { 
    // fetchedResultsController is class member var NSFetchedResultsController 
    id <NSFechedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] 
    objectAtIndex: section]; 
    NSInteger rows = [sectionInfo numberOfObjects]; 
    return rows + insertRows; 
} 
在委託的tableView

然後:numberOfRowsInSection :,我添加附件插入的行將其標記爲添加。

我從這次經歷中學到的教訓是,當一行被動態添加到表視圖中時,不需要在託管對象上下文中創建實體對象。該對象僅在提交編輯樣式(添加)的事件上創建。需要記住的另一件重要事情是,我必須跟上動態插入或刪除的行同步跟蹤部分中的行,如上所述。

順便說一句,我試圖添加一行到我的表視圖作爲一個用戶界面添加新的實體或數據的原因是基於iPhone的聯繫人應用程序。我知道添加新實體最常用的方法是在導航欄上顯示Add按鈕,但Contact應用程序提供了一種替代方法。如果您選擇一個人並觸摸導航欄上的編輯按鈕,則幾個添加行將以動畫方式顯示在表格視圖中。我不確定我的解決方案是否是實現此目標的正確方法。請糾正我,我想接受任何好的答案!