MPMediaItems 的 NSMutableArray 更快排序?代码审查

2024-03-09

我进入 iOS 编程已经几周了,还有很多东西要学。我有一种包含 MPMediaItems 的 NSMutableArray 正在工作,但是对于 1200 个项目,它大约慢 10 秒,我正在寻找一种更快的方法。

我的最终目标是拥有一系列 MPMediaItemCollection 项目,每个项目代表一个专辑。我无法从 MPMediaQuery 中获取此信息(据我所知),因为我需要从播放列表中获取歌曲。因此,我会对从特定播放列表(“过去 4 个月”)中获得的歌曲进行排序,然后构建我自己的收藏数组。正如我所说,下面的方法有效,但速度非常慢。即使我仅按 MPMediaItemPropertyAlbumTitle 排序,仍然需要大约 4 秒(iPhone 4S)。

编辑:我应该提到我尝试了排序描述符,但我无法获得工作的关键。例如。

NSSortDescriptor *titleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"MPMediaItemPropertyAlbumTitle" ascending:YES];

这会返回一个错误

[<MPConcreteMediaItem 0x155e50> valueForUndefinedKey:]: this class is not key value coding-compliant for the key MPMediaItemPropertyAlbumTitle.

The Code

MPMediaQuery *query = [MPMediaQuery playlistsQuery];
NSArray *playlists = [query collections];
NSMutableArray *songArray = [[NSMutableArray alloc] init];

for (MPMediaItemCollection *playlist in playlists) {
    NSString *playlistName = [playlist valueForProperty: MPMediaPlaylistPropertyName];
    NSLog (@"%@", playlistName);
    if ([playlistName isEqualToString:@"Last 4 months"]) {

        /* replaced this code with a mutable copy
        NSArray *songs = [playlist items];
        for (MPMediaItem *song in songs) {
            [songArray addObject:song]; 
        }
        */
        // the following replaces the above for-loop
        songArray = [[playlist items] mutableCopy ];

        [songArray sortUsingComparator:^NSComparisonResult(id a, id b) {
            NSString *first1 = [(MPMediaItem*)a valueForProperty:MPMediaItemPropertyAlbumTitle];
            NSString *second1 = [(MPMediaItem*)b valueForProperty:MPMediaItemPropertyAlbumTitle];

            NSString *first2 = [(MPMediaItem*)a valueForProperty:MPMediaItemPropertyAlbumPersistentID];
            NSString *second2 = [(MPMediaItem*)b valueForProperty:MPMediaItemPropertyAlbumPersistentID];

            NSString *first3 = [(MPMediaItem*)a valueForProperty:MPMediaItemPropertyAlbumTrackNumber];
            NSString *second3 = [(MPMediaItem*)b valueForProperty:MPMediaItemPropertyAlbumTrackNumber];

            NSString *first = [NSString stringWithFormat:@"%@%@%03d",first1,first2, [first3 intValue]];
            NSString *second = [NSString stringWithFormat:@"%@%@%03d",second1,second2, [second3 intValue]];

            return [first compare:second]; 
        }];
    }
}

我知道这是一个旧线程,但我认为澄清为什么 OP 排序代码不起作用很重要,这样任何遇到此代码的人都不会推迟使用 NSSortDescriptors。

代码:

[[NSSortDescriptor alloc] initWithKey:@"MPMediaItemPropertyAlbumTitle" ascending:YES];

应该:

[[NSSortDescriptor alloc] initWithKey:MPMediaItemPropertyAlbumTitle ascending:YES];

因为 MPMediaItemPropertyAlbumTitle 保存键的名称。

我已经多次使用过这段代码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MPMediaItems 的 NSMutableArray 更快排序?代码审查 的相关文章

随机推荐