从NSMutableArray中移除对象

3

我有两个元素:

NSMutableArray* mruItems;
NSArray* mruSearchItems;

我有一个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];

}    

错误: 现在我发现有些字符串没有用引号包括起来(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
)'

太混乱了,无法放在评论中,将其编辑到问题中。 - Ted
2
你正在枚举集合时进行编辑,这就是你的问题。 - Stefan H
我相信引号在问题中起了作用? - Ted
1
  1. 我喜欢你的数组内容。
  2. ASCII兼容字符串在日志输出中不会用引号表示。很奇怪,我知道。
- Morgan Harris
@MorganHarris,世界需要更多像那样的数组。 - Stefan H
谢谢,这是个好消息!@Morgan Harris +1 - Ted
2个回答

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

向前面的回答者(也是第一个回答者)@Michael Dautermann 表示无数的歉意。我很喜欢 Michael 的解决方案,从中也学到了新东西。不过,这个答案符合我的口味,简洁明了。谢谢! - Ted
我已删除了有问题的答案。我曾尝试继续使用"isEqualToString:"选择器,因为我认为"isEqual"和"isEqualToString:"在功能上不是完全相同的。我的判断是错误的。但是,在删除项目后,原始代码中的索引"i"与可变数组的顺序不一致,这一点我并没有错。 - Michael Dautermann

4

在枚举集合时,您不能编辑该集合。相反,应将索引存储起来,然后通过循环遍历索引数组进行删除操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接