检索iOS中上次播放时间sorting的歌曲列表

我需要从iOS设备获取N个最近播放的歌曲的列表。

目前唯一可以设想的方法是通过MPMediaQuery获取所有歌曲,并通过MPMediaQuery手动sorting。

这是一个潜在的昂贵的操作,我想知道是否有更好的方法。


编辑:经过一些testing,这是一个非常昂贵的操作。 在2500首歌曲的testing库中,花了大约20秒的时间:

  1. 得到所有的歌曲。
  2. 为所有从未播放的歌曲(1970年1月1日)分配一个date。
  3. 按datesorting。
  4. 取前N个条目。

任何改进build议,将不胜感激。


编辑2:现在解决,但只是为了logging这里是我在做什么。

我正在使用如下所述的块进行sorting: https : //stackoverflow.com/a/805589/112702 。 只要将分类方法改变为Bryan的答案,iPod Touch 3的速度就提高了近20倍。

一种方法是从MPMediaQuery获取MPMediaItem的数组,并使用NSSortDescriptor通过MPMediaItemPropertyLastPlayedDate进行NSSortDescriptor

 NSTimeInterval start = [[NSDate date] timeIntervalSince1970]; MPMediaQuery *songsQuery = [MPMediaQuery songsQuery]; NSArray *songsArray = [songsQuery items]; NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:MPMediaItemPropertyLastPlayedDate ascending:NO]; NSArray *sortedSongsArray = [songsArray sortedArrayUsingDescriptors:@[sorter]]; NSTimeInterval finish = [[NSDate date] timeIntervalSince1970]; NSLog(@"Execution took %f seconds.", finish - start); 

这种sorting方式是最近最先播放的。 我用2000首歌曲在iPhone 4S上testing了这个,耗时0.98秒。

我认为MPMediaQuery是目前从iOS设备上播放最近播放的歌曲的唯一方法。

您可以使用属性MPMediaItemPropertyLastPlayedDate ,它将返回用户播放媒体项目的最近日历date和时间。 值是一个NSDate对象。

http://developer.apple.com/library/IOs/#documentation/MediaPlayer/Reference/MPMediaItem_ClassReference/Reference/Reference.html#//apple_ref/doc/constant_group/General_Media_Item_Property_Keys