3

该代码可以工作并使用部分填充表格,但它有一个缺陷:它不会像原生音乐应用程序那样逃避标点符号和歌曲标题中的“The”前缀。

非常感谢一些关于我应该如何去做的指导。

- (void)viewDidLoad
{
    [super viewDidLoad];
    MPMediaQuery *songQuery = [MPMediaQuery songsQuery];
    self.songsArray = [songQuery items];
    self.sectionedSongsArray = [self partitionObjects:self.songsArray collationStringSelector:@selector(title)];
}

- (NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector
{
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    NSInteger sectionCount = [[collation sectionTitles] count];
    NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount];
    for(int i = 0; i < sectionCount; i++)
    {
        [unsortedSections addObject:[NSMutableArray array]];
    }
    for (id object in array)
    {
        NSInteger index = [collation sectionForObject:object collationStringSelector:selector];
        [[unsortedSections objectAtIndex:index] addObject:object];
    }
    NSMutableArray *sections = [NSMutableArray arrayWithCapacity:sectionCount];
    for (NSMutableArray *section in unsortedSections)
    {
        [sections addObject:[collation sortedArrayFromArray:section collationStringSelector:selector]];
    }
    return sections;
}
4

2 回答 2

5

我完全忽略了这一点。这里的答案是简单地使用MPMediaQuerySection. Apple 文档的存在是有原因的!

于 2012-11-06T03:33:24.740 回答
2

椰子 -

这是我用来索引包含我的音乐库中所有歌曲的查询的实现:

MPMediaQuery *allSongsQuery = [MPMediaQuery songsQuery];

// Fill in the all songs array with all the songs in the user's media library
allSongsArray = [allSongsQuery items];

allSongsArraySections = [allSongsQuery itemSections];

allSongsArraySections 是 MPMediaQuerySection 的 NSArray,每个都有一个标题和一个范围。零节的 NSArray 对象(在我的例子中,标题为 @"A")的 range.location 为 0,range.length 为 158。

当我的 UITableView 调用 numberOfRowsInSection 时,我返回每个部分的 range.length 值。我使用 cellForRowAtIndexPath 中的 range.location 值作为该部分的起始行,然后将 indexPath.row 添加到它以到达我需要从 allSongsArray 返回的单元格。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
....
    // Return the number of rows in the section.
    MPMediaQuerySection *allSongsArraySection = globalMusicPlayerPtr.allSongsArraySections[section];
    return allSongsArraySection.range.length;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
    MPMediaQuerySection *allSongsArraySection = globalMusicPlayerPtr.allSongsArraySections[indexPath.section];
    rowItem = [globalMusicPlayerPtr.allSongsArray objectAtIndex:allSongsArraySection.range.location + indexPath.row];
....
}

在使用它之前,我曾尝试通过自己编写来匹配原生音乐播放器的实现,但它的行为并不完全相同。不仅如此,本机索引速度要快得多!

于 2013-03-29T08:35:30.773 回答