艺术家的专辑数量

Jon*_*han 5 iphone mpmediaitem mpmediaitemcollection mpmediaquery

这是我的问题=)

MPMediaQuery *artistQuery = [MPMediaQuery artistsQuery];
NSArray *songsByArtist = [artistQuery collections];
Run Code Online (Sandbox Code Playgroud)

如何在songsByArtist中获取MPMediaItemCollections的每位艺术家的专辑数量?

例如:

披头士乐队的3张专辑

AC/DC 6专辑

谢谢 !!

Rin*_*lin 6

我使用谓词获得艺术家的专辑和歌曲数量:

MPMediaPropertyPredicate *artistNamePredicate = [MPMediaPropertyPredicate predicateWithValue:@"ArtistName" forProperty:MPMediaItemPropertyArtist];
MPMediaQuery *myComplexQuery = [[MPMediaQuery alloc] init];
[myComplexQuery addFilterPredicate: artistNamePredicate];
NSInteger songCount = [[myComplexQuery collections] count]; //number of songs
myComplexQuery.groupingType = MPMediaGroupingAlbum;
NSInteger albumCount = [[myComplexQuery collections] count]; //number of albums
Run Code Online (Sandbox Code Playgroud)


Bry*_*uby 5

artistsQuery便捷构造不排序,并通过专辑组.artistsQuery返回按艺术家姓名按字母顺序排序的所有艺术家的媒体项集合数组.嵌套在每个艺术家集合中的是与该艺术家的所有歌曲相关联的一系列媒体项目.嵌套数组按歌曲标题按字母顺序排序.

保持艺术家对专辑计数的一种方法是枚举每个艺术家集合的所有歌曲项目,并使用a NSMutableSet来跟踪与每首歌曲相关联的不同专辑标题.然后将集合的计数添加为a中每个艺术家键的值NSMutableDictionary.任何重复的专辑标题都不会被添加,因为NSMutableSet只会采用不同的对象:

MPMediaQuery *artistQuery = [MPMediaQuery artistsQuery];
NSArray *songsByArtist = [artistQuery collections];
NSMutableDictionary *artistDictionary = [NSMutableDictionary dictionary];
NSMutableSet *tempSet = [NSMutableSet set];

[songsByArtist enumerateObjectsUsingBlock:^(MPMediaItemCollection *artistCollection, NSUInteger idx, BOOL *stop) {
    NSString *artistName = [[artistCollection representativeItem] valueForProperty:MPMediaItemPropertyArtist];

    [[artistCollection items] enumerateObjectsUsingBlock:^(MPMediaItem *songItem, NSUInteger idx, BOOL *stop) {
        NSString *albumName = [songItem valueForProperty:MPMediaItemPropertyAlbumTitle];
        [tempSet addObject:albumName];
    }];
    [artistDictionary setValue:[NSNumber numberWithUnsignedInteger:[tempSet count]] 
                        forKey:artistName];
    [tempSet removeAllObjects];
}];
NSLog(@"Artist Album Count Dictionary: %@", artistDictionary);
Run Code Online (Sandbox Code Playgroud)

如果将查询更改为,则会更清晰albumsQuery.此查询按专辑名称对集合进行分组和排序.然后,只需要通过一系列专辑收藏进行枚举,并保持每个专辑的代表性艺术家名称的计数NSCountedSet.计数集将跟踪插入对象的次数:

MPMediaQuery *albumQuery = [MPMediaQuery albumsQuery];
NSArray *albumCollection = [albumQuery collections];
NSCountedSet *artistAlbumCounter = [NSCountedSet set];

[albumCollection enumerateObjectsUsingBlock:^(MPMediaItemCollection *album, NSUInteger idx, BOOL *stop) {
    NSString *artistName = [[album representativeItem] valueForProperty:MPMediaItemPropertyArtist];
    [artistAlbumCounter addObject:artistName];
}];
NSLog(@"Artist Album Counted Set: %@", artistAlbumCounter);
Run Code Online (Sandbox Code Playgroud)

您还可以NSCountedSet使用该countForObject:方法检索a中给定对象的计数.