Fido Fido - 1 month ago 10
Objective-C Question

How to remove multiple selected items in an UITableview by tapping a button ? iOS Objective-C

I have a UITableview on an UITableview Controller. I loaded the table view with the data and stored the selected values in an array called "selectedPsaData" so far.

I wanted to remove multiple selected cells from tableview1 by tapping the remove button.

Following code is for my "didSelectRowAtIndexPath". I want a proper Remove/Delete function for -

(IBAction)removeBtntapped:(id)sender{
}


Please help me since I am relatively new to Objective-C.

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

NSString *psaData =[self.loadedPSAData objectAtIndex:indexPath.row];
PSATableViewCell *cell=[tableView1 cellForRowAtIndexPath:indexPath];


[self.tableView1 deselectRowAtIndexPath:indexPath animated:YES];
// [self.tableView2 deselectRowAtIndexPath:indexPath animated:YES];

if([self isRowSelectedOnTableView:tableView1 atIndexPath:indexPath])
{
[self.selectedCells removeObject:indexPath];
[self.selectedPSAData removeObject:psaData];
cell.accessoryType =UITableViewCellAccessoryNone;
}
else{
[self.selectedCells addObject:indexPath];
[self.selectedPSAData addObject:psaData];

cell.accessoryType =UITableViewCellAccessoryCheckmark;
[self.tableView1 performSelector:@selector(reloadData) withObject:nil afterDelay:0.2];
}
NSLog(@"%@", self.selectedPSAData); //selected values are holding in this Array
}

Answer

With your current approach, you're going to get weird results while scrolling even if you get the 'remove' logic worked out (because the table view caches and reuses cells).

You should start by adding a BOOL selected property to your PSAData class. Then your selection method can become:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PSAData *psaData = [self.loadedPSAData objectAtIndex:indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (psaData.selected) {
        [self.selectedPSAData removeObject:psaData];
        psaData.selected = NO;
    } else {
        [self.selectedPSAData addObject:psaData];
        psaData.selected = YES;
    }
    [tableView reloadData];
}

To get the visual indicator, simply add a few lines inside tableView:cellForRowAtIndexPath:.

PSAData *psaData = [self.loadedPSAData objectAtIndex:indexPath.row];
if (psaData.selected) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
    cell.accessoryType = UITableViewCellAccessoryNone;
}

Finally, removing items is a case of matching array elements.

- (void)removeSelected:(id)sender
{
    for (id object in self.selectedPSAData) {
        [self.loadedPSAData removeObject:object];
    }
    [self.selectedPSAData removeAllObjects];
    [self.tableView reloadData];
}
Comments