Below is my code.
NSMutableArray *arr = [[NSMutableArray alloc] init]; [arr addObject:@"5"]; [arr addObject:@"7"]; [arr addObject:@"8"]; [arr enumerateObjectsUsingBlock:^(NSString *obj,NSUInteger idx,BOOL *stop) { [arr replaceObjectAtIndex:idx withObject:@"10"]; }];
In the exception log I got
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x742a580> was mutated while being enumerated.' *** First throw call stack: (0x1596012 0x12a3e7e 0x161ecc5 0x158fe1b 0x158fa16 0x158f925 0x2ba4 0x1e87b7 0x1e8da7 0x1e9fab 0x1fb315 0x1fc24b 0x1edcf8 0x25f8df9 0x25f8ad0 0x150bbf5 0x150b962 0x153cbb6 0x153bf44 0x153be1b 0x1e97da 0x1eb65c 0x29fd 0x2925) libc++abi.dylib: terminate called throwing an exception 0x1e87b7 0x1e8da7 0x1e9fab 0x1fb315 0x1fc24b 0x1edcf8 0x25f8df9 0x25f8ad0 0x150bbf5 0x150b962 0x153cbb6 0x153bf44 0x153be1b 0x1e97da 0x1eb65c 0x29fd 0x2925) *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x742a580> was mutated while being enumerated.' *** First throw call stack: (0x1596012 0x12a3e7e 0x161ecc5 0x158fe1b 0x158fa16 0x158f925 0x2ba4 0x1e87b7 0x1e8da7 0x1e9fab 0x1fb315 0x1fc24b 0x1edcf8 0x25f8df9 0x25f8ad0 0x150bbf5 0x150b962 0x153cbb6 0x153bf44 0x153be1b 0x1e97da 0x1eb65c 0x29fd 0x2925) libc++abi.dylib: terminate called throwing an exception
The code works fine when I use for loop
for (int i = 0 ; i< arr.count; i++) { [arr replaceObjectAtIndex:i withObject:@"8"]; }
So while I use enumerateObjectsUsingBlock, I get an exception. But both are enumerations. Right? Then why does the top code throw an exception was mutated while being enumerated ?
Nscry source share