iOS中检索特定艺术家的歌曲数量的最快方法是什么?



我试图检索本地iOS设备上的所有艺术家,以及每个艺术家,该艺术家可用的歌曲数量。

我目前正在以一种直接的方式进行此操作,通过查询所有艺术家,并为每个艺术家计算其集合中的项目(歌曲)数量:

MPMediaQuery *query = [[MPMediaQuery alloc] init];
[query setGroupingType:MPMediaGroupingArtist];
NSArray *collections = [query collections];
for (MPMediaItemCollection *collection in collections)
{
    MPMediaItem *representativeItem = [collection representativeItem];
    int songs = [[collection items] count];
    // do stuff here with the number of songs for this artist
}

然而,这似乎不是很有效,或者至少比我预期的要慢。

在一个有几百名美工的iPhone 4演示设备上,上面的代码运行了大约7秒。当我注释掉获取"集合项"计数的行时,时间减少到1秒。

所以我想知道是否有一种比我上面所做的更快的方法来检索艺术家的歌曲计数?


更新09/27/2011。我看到我可以简化歌曲计数检索的艺术家使用:

int songs = [collection count];

而不是我在做什么:

int songs = [[collection items] count];

然而,实际上这对性能几乎没有影响。

我借了一部iPhone 3G,在速度较慢的设备上测试这个问题的性能。

我的代码在这个3G上运行需要17.5秒,只有637首歌曲分布在308位艺术家身上。

如果我注释掉检索歌曲数量的行,那么同样的设备只需要0.7秒就可以完成…

一定有一种更快的方法来检索iOS设备上每个艺术家的歌曲数量。

经过进一步的研究和试验和错误,我认为最快的方法是使用artistsQuery查询媒体库,而不是循环遍历每个艺术家的集合,您可以使用NSNumbers的NSMutableDictionary来跟踪每个艺术家的歌曲数量。

使用下面的代码,我看到速度比我最初的方法提高了1.5倍到7倍,这取决于设备速度、艺术家数量和每个艺术家的歌曲数量。(增幅最大的是iPhone 3G,最初播放945首歌需要21.5秒,现在只需要2.7秒!)

如果我发现任何速度改进,我会编辑这个答案。请随时纠正任何直接在我的回答,因为我仍然是新的Objective-C和iOS api。(特别是,我可能会错过一个更快的方式来存储整数在哈希表比我有NSNumbers在一个NSMutableDictionary下面?)

NSMutableDictionary *artists = [[NSMutableDictionary alloc] init]; 
MPMediaQuery *query = [MPMediaQuery artistsQuery];
NSArray *items = [query items];
for (MPMediaItem *item in items)
{
     NSString *artistName = [item valueForProperty:MPMediaItemPropertyArtist];
    if (artistName != nil)
    {
        // retrieve current number of songs (could be nil)
        int numSongs = [(NSNumber*)[artists objectForKey:artistName] intValue];
        // increment the counter (could be set to 1 if numSongs was nil)
        ++numSongs;
        // store the new count
        [artists setObject:[NSNumber numberWithInt:numSongs] forKey:artistName];
    }
}

相关内容

最新更新