artistsQuery 便利构造函数不按专辑排序和分组。 artistsQuery 返回所有艺术家的媒体项目集合数组,按艺术家姓名的字母顺序排序。嵌套在每个艺术家集合中的是与该艺术家的所有歌曲相关联的媒体项数组。嵌套数组按歌曲名称的字母顺序排序。
按艺术家计算专辑数量的一种方法是枚举每个艺术家收藏的所有歌曲项目,并使用NSMutableSet 来跟踪与每首歌曲相关的不同专辑标题。然后将集合的计数添加为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);
如果将查询更改为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);
您还可以使用countForObject: 方法在NSCountedSet 中检索给定对象的计数。