Question

Can anyone pls suggest how to string element of an NSArray using fast enumeration. Its very easy to do the same with normal for loop. Below code works fine

_tempArray = [[NSMutableArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F", nil];

NSUInteger i=0;
for (; i<[_tempArray count]; i++) {
     if ([[_tempArray objectAtIndex:i] isEqualToString:@"A"]) {
            [_tempArray replaceObjectAtIndex:i withObject:@"a"];
      }
}

I want to do the same as above code does with fast enumeration. I tried the below code but it gives *****Error: Collection <__NSArrayM: 0x610000043090> was mutated while being enumerated.******, which means it is not possible to modify the collection while enumerating it. Can anyone suggest any way to achieve it.**

NSUInteger j=0;
    for (NSString *temp in _tempArray) {
        if ([temp isEqualToString:@"A"]) {
            [_tempArray replaceObjectAtIndex:j withObject:@"a"];
        }
        j++;
    }
Was it helpful?

Solution

How to modify string element of a NSArray using fast enumeration?

Don't. You are not supposed to modify the array during enumeration. It's not an arbitrary restriction -- doing so may result in logical errors.

If you want to modify/transform an array, then use an explicitly indexed for loop instead.

OTHER TIPS

You can tighten up the code with the array indexing syntax:

for (int i=0; i<_tempArray.count; i++) {
    if ([_tempArray[i] isEqualToString:@"A"]) {
        _tempArray[i] = @"a";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top