检索按iOS上次播放时间排序的歌曲列表 [英] Retrieve list of songs ordered by last play time in iOS
问题描述
我需要按顺序从iOS设备获取最近播放过的 N 首歌曲的列表.
I need to obtain a list of the N most recently played songs from an iOS device, in order.
目前,我能想象的唯一方法是通过MPMediaQuery
获取所有歌曲,然后按lastPlayedDate
对其进行手动排序.
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.
经过一些测试,这是一个非常昂贵的操作.在包含2500首歌曲的测试库中,花了大约20秒的时间:
After some tests, this is a very expensive operation. On a test library of 2500 songs, it took around 20 seconds to:
- 获取所有歌曲.
- 为所有从未播放过的歌曲指定日期(1970年1月1日).
- 按日期排序.
- 获取前 N 个条目.
- 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.
我正在按照此处所述使用块进行排序: https://stackoverflow.com/a/805589/112702 .只需将排序方法更改为Bryan的回答,就可以在iPod Touch 3上将速度提高近20倍.
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.
推荐答案
一种方法是获取从MPMediaQuery
获得的MPMediaItem
数组,并使用NSSortDescriptor
通过MPMediaItemPropertyLastPlayedDate
对其进行排序:
One way is to take the array of MPMediaItem
s you get from the MPMediaQuery
and sort it by MPMediaItemPropertyLastPlayedDate
using an NSSortDescriptor
:
NSTimeInterval start = [[NSDate date] timeIntervalSince1970];
MPMediaQuery *songsQuery = [MPMediaQuery songsQuery];
NSArray *songsArray = [songsQuery items];
NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:MPMediaItemPropertyLastPlayedDate
ascending:NO];
NSArray *sortedSongsArray = [songsArray sortedArrayUsingDescriptors:@[sorter]];
NSTimeInterval finish = [[NSDate date] timeIntervalSince1970];
NSLog(@"Execution took %f seconds.", finish - start);
这将按照最近播放的新数组对新数组进行排序.我在iPhone 4S上用2000首歌曲对其进行了测试,它花了0.98秒.
This sorts the new array by most recently played first. I tested this on a iPhone 4S using 2000 songs and it took .98 seconds.
这篇关于检索按iOS上次播放时间排序的歌曲列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!