i have some problem with two ways of iteration.
NSArray *array=[[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",nil];
NSMutableArray *mutArray=[[NSMutableArray alloc] initWithArray:array];
when i do like this then it’s working correct
for (int i=0;[mutArray count]!=0;) {
[mutArray removeObjectAtIndex:i];
}
NSLog(@"%d,",[mutArray count]);
But when i do like this, it’s crashing… why?
for(id obj in mutArray)
{
[mutArray removeObject:obj]
}
NSLog(@"%d,",[mutArray count]);
Please give me the solution for second case.
The second case is called fast enumeration. You can’t edit an array while it is being fast-enumerated, due to an implementation detail of fast enumeration.
I often get around this problem by doing the following:
This way you’re doing the iterating over a temporary copy of the array, but you can modify the original as you go through.
p.s. you can’t edit during fast enumeration because fast enumeration works by asking an object for a C array of the contents at the start of the enumeration. Once that has been obtained, the iteration is quick, because there are no Objective-C message calls between the enumerations. However, if you modify the array, the C array will no longer be a valid representation of the contents, so an exception is raised.