views:

472

answers:

1

I have a tableview with several sections. I would like to be able to move rows from one section into another and to delete a section once it has no rows. I am trying to do this through moveRowAtIndexPath but the code I have doesn't work and throws an NSRangeException exception.

Here is a code sample:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {

    NSUInteger fromSection = [fromIndexPath section];
    NSUInteger fromRow = [fromIndexPath row];
    NSString *fromKey = [self.keys objectAtIndex:fromSection];
    NSMutableArray *fromEventSection = [self.eventsDict objectForKey:fromKey];

    NSUInteger toSection = [toIndexPath section];
    NSUInteger toRow = [toIndexPath row];
    NSString *toKey = [self.keys objectAtIndex:toSection];
    NSMutableArray *toEventSection = [self.eventsDict objectForKey:toKey];

    id object = [[fromEventSection objectAtIndex:fromRow] retain];
    [fromEventSection removeObjectAtIndex:fromRow];
    [toEventSection insertObject:object atIndex:toRow];
    [object release];
    // The above code works just fine!

    // Try to delete an empty section. Here is where trouble begins:
    if ((fromSection != toSection) && [fromEventSection count] == 0) {
     [self.keys removeObjectAtIndex:fromSection];
     [self.eventsDict removeObjectForKey:fromKey];

     [tableView deleteSections:[NSIndexSet indexSetWithIndex:fromSection] withRowAnimation:UITableViewRowAnimationFade];
    }
A: 

Hi,

did you get an answer for this. I can't figure it out either

Nate
Not exactly. But I did work around it as follows:I stopped trying to delete the empty sections while the user is moving rows around and instead opted to delete the empty sections once the user is done with editing. However, even then, deleting and empty section did not work correctly (I suspect an Apple bug). So in order to delete the empty sections I ended up adding a row of zero height into each of my empty sections and then deleting the sections.Take a look at this demo in YouTube: http://tinyurl.com/ycg4uhs to see if this approach would work for you.
Sergio