Search code examples
iphoneuitableviewinsertrownsindexpath

insert/create new row in a same section of uitableview


I am stuck in a problem, I have a uitableview with rows let say 5. If a user selects one row then a new row exactly beneath the tapped row should be created/inserted with an animation (as we have seen with sections hiding/unhiding) and upon tap of the newly inserted row it should be deleted.

I have given a try but it says


Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid  
update: invalid number of rows in section 0.  The number of rows contained in an existing section 
after the update (6) must be equal to the number of rows contained in that section before the update 
(5), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted).'

so what should be the other way to achieve this functionality ? Thanks in advance.


Solution

  • 
    - (NSInteger)numberOfRowsInSection:(NSInteger)section {
        switch (section) {
            case 0:
                return numberOfRows;
        }
        return 0;
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
        numberOfRows ++;
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        NSMutableArray*  tempArray = [[NSMutableArray alloc] init];
            [tempArray addObject:[NSIndexPath indexPathForRow:indexPath.row +1  inSection:indexPath.section]];
        [tableView beginUpdates];
        [tableView insertRowsAtIndexPaths:tempArray withRowAnimation:UITableViewRowAnimationRight];
        [tableView endUpdates]; 
        [tempArray release];
    
    }
    
    
    
    

    I was making 2 mistakes 1) I wasnot using [tableView beginUpdates] and obviously [tableView endUpdates] after updation 2) The method to calculate the indexpath for a newRow was ambigious.

    Thankyou very much pratikshabhisikar and Max Howell for putting your time and efforts in.