私はiOSプログラミングを始めて数週間で、学ぶことがたくさんあります。MPMediaItemsを含むNSMutableArrayのようなものが機能していますが、1200のアイテムのようなものでは、約10秒遅く、より高速なアプローチを探しています。
私の最終的な目標は、それぞれがアルバムを表すMPMediaItemCollectionアイテムの配列を作成することです。プレイリストから曲を取得する必要があるため、MPMediaQueryからこれを取得することはできません(私が知る限り)。そのため、特定のプレイリスト(「過去4か月」)から取得した曲を並べ替えてから、独自のコレクションの配列を作成します。私が言うように、以下のアプローチは機能しますが、非常に遅いです。MPMediaItemPropertyAlbumTitleだけで並べ替えても、約4秒かかります(iPhone4S)。
編集:ソート記述子を試しましたが、キーを機能させることができません。例えば
NSSortDescriptor *titleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"MPMediaItemPropertyAlbumTitle" ascending:YES];
これはのエラーを返します
[<MPConcreteMediaItem 0x155e50> valueForUndefinedKey:]: this class is not key value coding-compliant for the key MPMediaItemPropertyAlbumTitle.
コード
MPMediaQuery *query = [MPMediaQuery playlistsQuery];
NSArray *playlists = [query collections];
NSMutableArray *songArray = [[NSMutableArray alloc] init];
for (MPMediaItemCollection *playlist in playlists) {
NSString *playlistName = [playlist valueForProperty: MPMediaPlaylistPropertyName];
NSLog (@"%@", playlistName);
if ([playlistName isEqualToString:@"Last 4 months"]) {
/* replaced this code with a mutable copy
NSArray *songs = [playlist items];
for (MPMediaItem *song in songs) {
[songArray addObject:song];
}
*/
// the following replaces the above for-loop
songArray = [[playlist items] mutableCopy ];
[songArray sortUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first1 = [(MPMediaItem*)a valueForProperty:MPMediaItemPropertyAlbumTitle];
NSString *second1 = [(MPMediaItem*)b valueForProperty:MPMediaItemPropertyAlbumTitle];
NSString *first2 = [(MPMediaItem*)a valueForProperty:MPMediaItemPropertyAlbumPersistentID];
NSString *second2 = [(MPMediaItem*)b valueForProperty:MPMediaItemPropertyAlbumPersistentID];
NSString *first3 = [(MPMediaItem*)a valueForProperty:MPMediaItemPropertyAlbumTrackNumber];
NSString *second3 = [(MPMediaItem*)b valueForProperty:MPMediaItemPropertyAlbumTrackNumber];
NSString *first = [NSString stringWithFormat:@"%@%@%03d",first1,first2, [first3 intValue]];
NSString *second = [NSString stringWithFormat:@"%@%@%03d",second1,second2, [second3 intValue]];
return [first compare:second];
}];
}
}