Search code examples
iosobjective-cnssortdescriptormpmediaquery

Sorting ipod playlists by ID


Im trying to fetch all the user's playlists from iPod and sort them by playlist's ID.
This is what I did so far:

MPMediaQuery *allPlaylistsQuery = [MPMediaQuery playlistsQuery];
NSArray *allPlaylists = [allPlaylistsQuery collections];
NSArray *sortedPlaylists = [allPlaylists sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:MPMediaPlaylistPropertyPersistentID ascending:YES]]];  

But I get exception:

'[<MPConcreteMediaPlaylist 0x14f38590> valueForUndefinedKey:]: this class is not key value coding-compliant for the key playlistPersistentID.'  

So whats the easiest (and efficiet) why to do such sort?


Solution

  • The reason for the exception is that MPMediaItem uses the method valueForProperty: to query property values, rather than valueForKey: which would make it KVC-compliant. Why is doesn't support valueForKey: is a bit of a mystery to me as it would make the class much more useful, for example the code you supplied in your question would have worked I reckon.

    Untested:

    MPMediaQuery *allPlaylistsQuery = [MPMediaQuery playlistsQuery];
    NSArray *allPlaylists = [allPlaylistsQuery collections];
    NSArray *sorted = [allPlaylists sortedArrayUsingComparator:^(id obj1, id obj2) {
        NSNumber *id1 = [(MPMediaItem *)obj1 valueForProperty:MPMediaItemPropertyPersistentID];
        NSNumber *id2 = [(MPMediaItem *)obj2 valueForProperty:MPMediaItemPropertyPersistentID];
        return [id1 compare:id2];
    }];