I have a tableView where I would like to delete the cells of the sections and if it is the last, instead of deleting the section too, I wanted to add a new cell with a new string: @ "there are no cells in this section". For some reason the code below is not working.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSMutableArray *spotType = [self spotsWithSection: section];
return spotType.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSUInteger section = indexPath.section;
NSUInteger row = indexPath.row;
NSMutableArray *thisSpotContainer = [self spotsWithSection:section];
Spot *s = (Spot*)thisSpotContainer[row];
cell.textLabel.text = s.name;
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSMutableArray *thisSpotContainer = [self spotsWithSection: indexPath.section];
if ([thisSpotContainer count] > 0) {
[tableView beginUpdates];
[thisSpotContainer removeObjectAtIndex:[indexPath row]];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
if ([thisSpotContainer count] == 0) {
NSArray *noSpotsHere = [NSArray arrayWithObjects:@"This section has no spots.", nil];
[thisSpotContainer insertObject:noSpotsHere atIndex:0];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
[tableView endUpdates];
}
}
}
- (NSMutableArray*) spotsWithSection:(NSUInteger)section {
NSArray * Spots = [Spot allSpots];
NSPredicate *predicate;
switch (section) {
case 0:
predicate = [NSPredicate predicateWithFormat:@"type = %@", @"restaurant"];
spotRest = [[Spots filteredArrayUsingPredicate:predicate] mutableCopy];
return spotRest;
break;
case 1:
predicate = [NSPredicate predicateWithFormat:@"type = %@", @"bar"];
spotBar = [[Spots filteredArrayUsingPredicate:predicate] mutableCopy]; return spotBar;
break;
case 2:
predicate = [NSPredicate predicateWithFormat:@"type = %@", @"club"];
spotClub = [[Spots filteredArrayUsingPredicate:predicate] mutableCopy];
return spotClub;
break;
}
}