17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSMutableArrayの要素を削除の落とし穴

Last updated at Posted at 2012-11-10
for (id object in array.reverseObjectEnumerator) {
    // objectを削除する必要があるかどうかチェックする
    if ([object shoudRemove]) {
        // objectを削除する
        [array removeObject:object];
    }
}

というコードを見かけたのですが、これはちょっとどうなのかな?
と思いました。
なぜならremoveObjectが配列では定数時間ではないからです。
コードでは1重ループのはずが、内部的には2重ループをまわしていることになるのです。
NSArrayにはfilteredArrayUsingPredicate、
NSMutableArrayにはfilterUsingPredicateが使えるので、こちらを使うのが良いんじゃないかと思います。

コレクションのサイズが大きくなると、この速度差は歴然だと思います。
実装によっては深刻なボトルネックにもなりかねません。
※もちろん要素数が少ないならばどっちでもいいです。

NSPredicateではblocksを使ってやるのが一番使いやすいかなとおもいます。

NSMutableArray *array = [@[@1, @2, @3, @4, @5] mutableCopy];
[array filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSNumber *evaluatedObject, NSDictionary *bindings) {
            return evaluatedObject.intValue > 2;
        }]];
NSLog(@"%@", array);
17
17
0

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
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?