假如我们有一个数组:
NSMutableArray *array = [NSMutableArrayarrayWithArray:@[@1,@5,@8]]
现在要删除元素5
for (NSNumber *x in array) {
if ([x intValue] == 5) {
[array removeObject:x];
}
}
这样会引起运行时错误,程序奔溃,log输出:
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x10010ff60> was mutated while being enumerated.'
所以换用下面的方法
//0快速迭代
NSNumber *xToRemove =nil;
for (NSNumber *xin array) {
if ([xintValue] ==5) {
xToRemove = x;
}
}
if (xToRemove) {
[array removeObject:xToRemove];
}
代码看起来很不简洁,我们也可以用下面两种迭代方法来移除元素:
//1普通迭代
for (int i=0; i<array.count; i++) {
NSNumber *x = array[i];
if ([xintValue] ==5) {
[array removeObject:x];
}
}
//2block迭代
[array enumerateObjectsUsingBlock:^(NSNumber *x,NSUInteger index,BOOL *stop) {
if ([xintValue] ==5) {
[array removeObject:x];
}
}];