如果您不想创建临时或新数组,可以使用以下命令:
NSMutableArray *array = ...; // your mutable array
NSIndexSet *toBeRemoved = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
// The block is called for each object in the array.
BOOL removeIt = ...; // YES if the element should be removed and NO otherwise
return removeIt;
}];
[array removeObjectsAtIndexes:toBeRemoved];
Run Code Online (Sandbox Code Playgroud)
NSIndexSet(但是使用了临时的。)
备注:我的想法是,“一次”删除所有匹配元素可能比在迭代期间单独删除每个元素更有效,如 Richard J. Ross III 所建议的那样。
但简短的测试表明情况并非如此。在我的计算机上,使用这两种方法从包含 1000000 个元素的数组中删除每隔一个元素所需的时间几乎相同。