从NSMutableArray中删除对象

Ted*_*Ted 3 xcode objective-c nsmutablearray ios

我有两个要素:

NSMutableArray* mruItems;
NSArray* mruSearchItems;
Run Code Online (Sandbox Code Playgroud)

我有一个基本上UITableView保持mruSearchItems,并且一旦用户滑动并删除特定行,我需要在其中找到该字符串的所有匹配mruItems并从那里删除它们.

我没有充分使用NSMutableArray,我的代码由于某些原因给了我错误:

- (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];

}    
Run Code Online (Sandbox Code Playgroud)

}

错误:我现在看到一些字符串不在引号之间(UTF8中的字符串是)

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
)'
Run Code Online (Sandbox Code Playgroud)

Nik*_*uhe 6

您得到一个例外,因为您在迭代其元素时正在改变容器.

removeObject:完成您正在寻找的东西:删除所有与参数相等的对象.

- (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];
}
Run Code Online (Sandbox Code Playgroud)