OGeek|极客世界-中国程序员成长平台

标题: ios - 在 iOS 中检索特定艺术家的歌曲数量的最快方法是什么? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 17:40
标题: ios - 在 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 秒。

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


2011 年 9 月 27 日更新。 我发现我可以使用这个来简化艺术家的歌曲计数检索:

int songs = [collection count];

而不是我在做什么:

int songs = [[collection items] count];

然而,实际上这对性能影响不大。

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

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

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

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



Best Answer-推荐答案


经过进一步研究和反复试验,我认为最快的方法是使用 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];
    }
}

关于ios - 在 iOS 中检索特定艺术家的歌曲数量的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7561251/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4