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

时间:2011-09-26 20:59:26

标签: ios mpmediaitem

我正在尝试检索本地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在较慢的设备上试试这个问题的性能。

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

如果我注释掉检索歌曲数量的行,那么相同的设备只需0.7秒即可完成......

必须有更快的方法来检索iOS设备上每位艺术家的歌曲数量。

1 个答案:

答案 0 :(得分:4)

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

使用下面的代码,我看到的速度提升了1.5倍到7倍,这取决于设备速度,艺术家数量和每位艺术家的歌曲数量。 (最大的增长是iPhone 3G,最初为945首歌曲花了21.5秒,现在需要2.7秒!)

如果我发现任何速度提升,我会编辑这个答案。请随意在我的回答中直接更正任何内容,因为我还是Objective-C和iOS API的新手。 (特别是,我可能会错过一个更快的方法来存储哈希表中的整数,而不是我在NSMutableDictionary中使用NSNumbers下面的内容?)

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];
    }
}