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

标签 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 来尝试在速度较慢的设备上解决此问题的性能。

我的代码在 308 位艺术家中只有 637 首歌曲的 3G 上运行需要 17.5 秒。

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

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

最佳答案

经过进一步的研究和反复试验,我相信最快的方法是使用artistsQuery查询媒体库,而不是循环遍历每个艺术家的收藏,而是跟踪歌曲的数量每个艺术家使用 NSNumbers 的 NSMutableDictionary。

使用下面的代码,我发现速度比最初的方法提高了 1.5 倍到 7 倍,具体取决于设备速度、艺术家数量以及每个艺术家的歌曲数量。 (增幅最大的是 iPhone 3G,最初需要 21.5 秒才能播放 945 首歌曲,现在只需要 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/

相关文章:

ios - 捏合手势以展开 UICollectionView Cell

iOS 按钮操作不起作用

ios - 为什么 MPMediaEntity/MPMediaItem 使用 valueForProperty?

iphone - MPMediaItemCollection整个库?

ios - 无法将专辑封面设置为背景颜色

ios - iOS 内存对齐错误

ios - 数组中字符串的 UISearchBar

ios - 适用于 iOS 的 Magical Record 和 SQLCipher - NSPersistentStore 创建返回 nil

objective-c - 从 iOS 库中选择音乐并发送/保存

ios - 在 MPMusicPlayerController 中随机播放 MPMediaItemCollection,但让用户选择第一项?