14
14

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.

ALAssetの日付順ソート最適化

Last updated at Posted at 2012-12-11

ALAssetsLibraryでユーザーの画像をもらって日付ソートしたくなりました。
(ALAssetの日付にはいろいろ問題もあるようですが、ここでは触れません)

アセットの配列が取れたのでソートしようとして次のコードを書きました。

[assetList sortWithOptions:NSSortConcurrent usingComparator:^NSComparisonResult(ALAsset *a, ALAsset *b) {
                                             NSDate *datea = [a valueForProperty:ALAssetPropertyDate];
                                             NSDate *dateb = [b valueForProperty:ALAssetPropertyDate];
                                             return [dateb compare:datea];
                                         }];

しかしこれがどうも遅い。
InstrumentsのTimeProfilerで調べてみると、valueForProperty:ALAssetPropertyDateが遅いようです。
なので、あらかじめ配列は、
[assetList addObject:@{@0 : asset, @1 : [asset valueForProperty:ALAssetPropertyDate]}];
のようにあらかじめ日付をいれておくことにします。
ほんとはkeyをもっと分かりやすくしたほうがいいのですが、パフォーマンス上文字列比較はしたくないので、整数値にします。

そして、

[assetList sortWithOptions:NSSortConcurrent usingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
                                             NSDate *datea = a[@1];
                                             NSDate *dateb = b[@1];
                                             return [dateb compare:datea];
                                         }];

のようにします。するとびっくり相当早い。
これにて満足のいく速度となりました。
比較する部分は非常に何度も呼ばれる部分なので、注意深く実装したいですね。
なお、マルチコアのデバイスならば、NSSortConcurrentが地味に効果的でした。
よりソートの日付精度が欲しい場合は、NSDateのtimeIntervalSince1970を使うといいようですね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?