Search code examples
iosobjective-cuitableviewnsarray

Reorder NSArray based on UITableView Edit


I have an app filled with over 500 songs for churches. I am adding a new feature, which will allow them to create a "slide show" of manually chosen songs. The way the layout is now is that they have a UITableView of all the songs, and tapping a song adds that PPT's file location to an NSArray, and adds a checkmark to the row. Following this, they can click the Preview button, which will give them a tableview of just the songs they have chosen, in the order they chose it.

I would like to allow editing mode to delete songs, or reorder them, but am not sure how to have that also reorder the NSArray, so that item 0 will be the first song they have on the tableview, not just the first one they tapped.


Solution

  • I assume you have an array of songs, called songsArray which is used to populate table view. Then when reordering happens, add this method.

    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
        NSObject *songToMove = [self.songsArray objectAtIndex:sourceIndexPath.row];
        [self.songsArray removeObjectAtIndex:sourceIndexPath.row];
        [self.songsArray insertObject:stringToMove atIndex:destinationIndexPath.row];
    }
    

    Dont forget to implement canMoveForRowAtIndexPath

    - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
       return YES;
    }
    

    This lets user to reorder all rows in your table view, if you don't want to let user to reorder specific rows, add check for indexPath.row and return NO for that row.