Search code examples
iosmpmediaitem

Getting The Corresponding MPMediaItem With MPMediaItemPropertyPersistentID


I need to retrieve the corresponding MPMediaItem with the persistent ID I stored using NSUserDefaults. My current way of doing this is to get all the MPMediaItems, loop through them, and find out the one that has the same persistent ID that I stored. I think this is a really bad performance, so is there an existing method in getting the MPMediaItem with the persistent ID that I have? I checked the documentation of Apple, but I was unable to find one.


Solution

  • You can get better than linear performance by looking up your MPMediaItem the items with a unique ID query:

    MPMediaQuery*   query = [MPMediaQuery songsQuery];  // general songs query
    
    MPMediaPropertyPredicate* pred = [MPMediaPropertyPredicate predicateWithValue:persistentID
                                                                      forProperty:MPMediaItemPropertyPersistentID];
    // narrow the query down to just items with that ID
    [query addFilterPredicate:pred];
    
    // now get items (there should be only one):
    MPMediaItem *item = [query.items firstObject];