Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove object from NSMutableArray

I have two elements:

NSMutableArray* mruItems;
NSArray* mruSearchItems;

I have a UITableView that holds the mruSearchItems basically, and once the user swipes and deletes a specific row, I need to find ALL matches of that string inside the mruItems and remove them from there.

I haven't used NSMutableArray enough and my code gives me errors for some reason:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
    //add code here for when you hit delete
    NSInteger i;
    i=0;
    for (id element in self.mruItems) {
        if ([(NSString *)element isEqualToString:[self.mruSearchItems objectAtIndex:indexPath.row]]) {

            [self.mruItems removeObjectAtIndex:i];
        }
        else
           {
            i++;
           }
    }
    [self.searchTableView reloadData];

}    

}

Error: I see now that some of the strings are not between quotation marks (the ones in UTF8 are though)

Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x1a10e0> was mutated while being enumerated.(
    "\U05de\U05e7\U05dc\U05d3\U05ea",
    "\U05de\U05d7\U05e9\U05d1\U05d5\U05df",
    "\U05db\U05d5\U05e0\U05df",
    "\U05d1 ",
    "\U05d1 ",
    "\U05d1 ",
    "\U05d1 ",
    Jack,
    Beans,
    Cigarettes
)'
like image 914
Ted Avatar asked Dec 05 '25 18:12

Ted


2 Answers

You get an exception because you are mutating a container while iterating over its elements.

removeObject: does exactly what you're looking for: removing all objects that are equal to the argument.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle != UITableViewCellEditingStyleDelete)
        return;

    NSString *searchString = [self.mruSearchItems objectAtIndex:indexPath.row];
    [self.mruItems removeObject:searchString];
    [self.searchTableView reloadData];
}
like image 189
Nikolai Ruhe Avatar answered Dec 08 '25 12:12

Nikolai Ruhe


You cannot edit the collection while enumerating through it, instead, store the indexes away, and then remove them afterwards by looping through your array of indexes.

like image 40
Stefan H Avatar answered Dec 08 '25 10:12

Stefan H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!