I have a tableview that is crashing when you swipe left to delete. It crashes after the deletion when the tableview reloads at a point in cellfor row atindexpath that references the indexpath. The other wrinkle is that table does not reload until receipt of notice of a successful deletion on the server. Nevertheless, I can't figure out what is causing the crash. Is there another delegate needed. Do I have to manually change the indexpath? Thanks in advance for any ideas or suggestions.
Here is my code:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == _myTableView ) {
if (editingStyle == UITableViewCellEditingStyleDelete) {
Items *itemToDelete = [_myItems objectAtIndex:indexPath.row];
NSNumber *iidToDelete = itemToDelete.iid;
//CREATE DICTIONARY AND SEND TO SERVER FOR DELETION
[self postToServerDelete:data andItem:itemToDelete];
}
}
}
-(void) postToServerDelete: (NSData *) data andItem:(Items *)itemToDelete {
//SEND TO SERVER
if (successint==1) {
dispatch_async(dispatch_get_main_queue(), ^{
[_managedObjectContext deleteObject:itemToDelete];
NSError* error;
[self getItems];//refreshes items list from managedobjectcontext
if ([_managedObjectContext save:&error]) {
[_myTableView reloadData];
}
});
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
static NSString *StepRowIdentifier = @"RowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:RowIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RowIdentifier] ;
}
//LINE WHERE CRASH OCCURS
Items* item = [[self getItems] objectAtIndex:indexPath.row];
NSString *steptext= item.name;
cell.textLabel.text=name;
return cell;
}
This crash line
Items* item = [[self getItems] objectAtIndex:indexPath.row];
Basically could be caused by 2 things:
- self getItems is returning other than array (or null).
- if it does return an array, then the index at which you specified no longer exist.
I suspect it is case 2, since you mention about deletion. And I see code, you seem to delete _myItems, but you refer to [self getItems] in cellForRow. These two need to be the same object.