I am using fmdb to manage some data that is display on a regular UITableView. I am attempting to delete one cell using this code:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
[db beginTransaction];
NSString * stringtoInsert = [NSString stringWithFormat: @"DELETE FROM TTLogObject WHERE id='%@'", [idArray objectAtIndex:indexPath.row]];
BOOL success = [db executeUpdate:stringtoInsert];
if (!success)
{
NSLog(@"insert failed!!");
}
NSLog(@"Error %d: %@", [db lastErrorCode], [db lastErrorMessage]);
[db commit];
[db close];
[self getList];
}
}
Here is the code for viewDidLoad and the getList function that I am using.
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
shipperCityArray = [[NSMutableArray alloc] init];
pickupDateArray = [[NSMutableArray alloc] init];
paidArray = [[NSMutableArray alloc] init];
idArray = [[NSMutableArray alloc] init];
//NSString *path = [[NSBundle mainBundle] pathForResource:@"tt" ofType:@"db"];
[self getList];
}
- (void)getList
{
db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[shipperCityArray removeAllObjects];
[pickupDateArray removeAllObjects];
[paidArray removeAllObjects];
[idArray removeAllObjects];
[db open];
FMResultSet *fResult= [db executeQuery:@"SELECT * FROM TTLogObject"];
while([fResult next])
{
[shipperCityArray addObject:[fResult stringForColumn:@"shipperCity"]];
[pickupDateArray addObject:[fResult stringForColumn:@"pickupDate"]];
[paidArray addObject:[NSNumber numberWithBool:[fResult boolForColumn:@"paid"]]];
[idArray addObject:[NSNumber numberWithInteger:[fResult intForColumn:@"id"]]];
NSLog(@"%@", [NSNumber numberWithInteger:[fResult intForColumn:@"id"]]);
}
[db close];
[self.tableView reloadData];
}
The issue is that the data gets deleted just fine from the database. However, after delete is pressed, the table view does not display any cells anymore. When I restart the app, the proper data gets loaded again, with the cell that was deleted actually gone. I suspect it has something to do with numberOfRowsInSection
.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(@"%i", [shipperCityArray count]);
return [shipperCityArray count];
}
When the app is launched, it prints the proper amount of cells, but when delete is hit, it does not print anything, and seems to not be called.
I have attempted to use [self.tableView beginUpdates]
and [self.tableView endUpdates]
but those seem to error out stating something about the wrong number of items resulting after the delete. I am not sure how to solve this. If I must use beginUpdates and endUpdates, can someone explain to me how this should be done properly, and what is actually going on?