Add new item to UITableView and Core Data as data source?
Posted
by David.Chu.ca
on Stack Overflow
See other posts from Stack Overflow
or by David.Chu.ca
Published on 2010-04-13T03:54:23Z
Indexed on
2010/04/13
4:52 UTC
Read the original article
Hit count: 990
iphone
I have trouble to add new item to my table view with core data. Here is the brief logic in my codes. In my ViewController class, I have a button to trigle the edit mode:
- (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 { ...}
}
In this block of codes, I added a new item to my current managed object context first, and then I added a new row to my tv. I think that both the number of objects in my data source or context and the number of rows in my table view should be 1.
However, I got an exception in the event of tabView:numberOfRowsInSection:
Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).
The exception was raised right after the delegate event:
- (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;
}
In debug mode, I found that the rows was still 0 and the event invoked after the the even of toggleEditing. It looks like that sectionInfo obtained from fetchedResultsController did not include the new entity object inserted. Not sure if I miss anything or steps? I am not sure how it works: to get the fetcedResultsController notified or reflect the change when a new entity is inserted into the current managed object context?
© Stack Overflow or respective owner