LoginSignup
10
10

More than 5 years have passed since last update.

[Objective-C] 配列から特定要素を安全に削除する

Posted at

イテレーション中に削除はできないので、以下のように削除用配列を作ってまるっと消すのがいいみたい。

int main() {
    NSMutableArray *array = [@[@1, @2, @1, @3, @1, @4, @1, @5] mutableCopy];
    NSMutableArray *discards = [NSMutableArray array];

    for (NSNumber *n in array) {
        if ([n isEqualToNumber:@1]) {
            [discards addObject:n];
        }
    }

    [array removeObjectsInArray:discards];

    NSLog(@"Result: %@", array);

    return 0;
}

実行結果。

2014-09-02 12:28:27.298 sample[57334:507] Result: (
    2,
    3,
    4,
    5
)
10
10
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10