I need to obtain a list of the N most recently played songs from an iOS device, in order.
The only way I can imagine doing it, at the moment, is by getting all the songs through an MPMediaQuery
and manually sort them by lastPlayedDate
.
This is a potentially expensive operation and I was wondering if there was a better approach.
Edit: After some tests, this is a very expensive operation. On a test library of 2500 songs, it took around 20 seconds to:
- Get all the songs.
- Assign a date to all songs that had never played (January 1 1970).
- Order them by date.
- Fetch the first N entries.
Any suggestion of improvements would be appreciated.
Edit 2: Solved now, but just for the record here's what I was doing.
I was sorting using a block as described here: https://stackoverflow.com/a/805589/112702. Simply changing the sorting method to what's in Bryan's answer improved my speed by nearly 20 times on an iPod Touch 3.