我很難用核心數據添加新項目到我的表格視圖。以下是我的代碼中的簡要邏輯。在我的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通知或反映更改?