Search code examples
iosiphonesqlitetableviewsql-delete

Sqlite database and swipe to delete


The project I'm working on required me to use a sqlite database, and I've been trying to get swipe to delete to work on my tableView:

[self performSelectorOnMainThread:@selector(removeMovieFromCache:) withObject:[NSNumber numberWithInt:movieId] waitUntilDone:YES];
    [db performSelectorOnMainThread:@selector(performQuery:) withObject:[NSString stringWithFormat:@"DELETE FROM movie WHERE id = %d", movieId] waitUntilDone:YES];
    [db performSelectorOnMainThread:@selector(performQuery:) withObject:[NSString stringWithFormat:@"DELETE FROM new_movies WHERE new_movie_id = %d", movieId] waitUntilDone:YES];
    [self removeMovieFromCache:movieId];
    [db performQueryWithFormat:@"DELETE FROM movie WHERE id = %d", movieId];
    [db performQueryWithFormat:@"DELETE FROM new_movies WHERE new_movie_id = %d", movieId];
    [db performQuery:@"COMMIT"];

That's the code to get rid of something from my database. When I try to apply this to my swipe to delete command of:

-

(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)movieID
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {        

      //code goes here        
    }
}

It just doesn't want to work, what am I doing wrong?


Solution

  • In your tableView Data Source, try implementing this:

    (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath 
    {
       return UITableViewCellEditingStyleDelete;
    }
    
    
    (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
    {
       return YES;
    }
    
    (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)movieID
    {
        if (editingStyle == UITableViewCellEditingStyleDelete)
        {       
           // First delete the row from the table, then delete from the DB, finally reload the date in the table 
           [theTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
           // code to delete from DB
           [theTable reloadData];        
        }
    }
    

    (replace "theTable" with whatever you've called your table!)