The artistsQuery
convenience constructor does not sort and group by album. artistsQuery
returns an array of media item collections of all artists sorted alphabetically by artist name. Nested inside each artist collection is an array of media items associated with all songs for that artist. The nested array is sorted alphabetically by song title.
One way to keep a count of albums by artist is to enumerate through all the song items for each artist collection and use a NSMutableSet
to keep track of distinct album titles associated with each song. Then add the count of the set as the value for each artist key in a NSMutableDictionary
. Any duplicate album titles will not be added since a NSMutableSet
will only take distinct objects:
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);
It would be cleaner if you change the query to albumsQuery
. This query groups and sorts the collection by album name. Then it is just a matter of enumerating through the array of album collections and keeping a count of the representative artist name for each album in a NSCountedSet
. The counted set will track the number of times objects are inserted:
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);
You can also retrieve the count for a given object in a NSCountedSet
with the countForObject:
method.