5

for我可以在没有副作用的情况下删除我在 Objective-C 循环中循环的项目吗?

例如,这样可以吗?

for (id item in items) {
   if ( [item customCheck] ) {
      [items removeObject:item];   // Is this ok here?
}
4

3 回答 3

12

不,如果在快速枚举 for 循环中对数组进行变异,则会出现错误。制作数组的副本,对其进行迭代,然后从原始数组中删除。

NSArray *itemsCopy = [items copy];

for (id item in itemsCopy) {
   if ( [item customCheck] )
      [items removeObject:item];   // Is this ok here
}

[itemsCopy release];
于 2011-04-28T23:46:41.153 回答
3

没有:

枚举是“安全的”——枚举器有一个突变保护,因此如果您在枚举期间尝试修改集合,则会引发异常。

使用枚举器中给出了更改要枚举的数组的选项:复制数组并枚举,或者建立一个索引集,以便在循环后使用。

于 2011-04-28T23:48:33.490 回答
0

你可以像这样删除:

    //Create array
    NSMutableArray* myArray = [[NSMutableArray alloc] init];

    //Add some elements
    for (int i = 0; i < 10; i++) {
        [myArray addObject:[NSString stringWithFormat:@"i = %i", i]];
    }

    //Remove some elements =}
    for (int i = (int)myArray.count - 1; i >= 0 ; i--) {
        if(YES){
            [myArray removeObjectAtIndex:i];
        }
    }
于 2015-05-15T14:14:38.713 回答