我正在为表格视图创建索引部分,以显示 iPod 库中的歌曲标题。为此,我使用 sectionForObject:collationStringSelector: 循环遍历歌曲查询中的所有 mediaItems。以下代码在 viewDidLoad 中执行,以获取表的节数和每个节的行数:
// Go through the collection of songs and collate them into sections A-Z
for (MPMediaItemCollection *arrayItem in itemsFromSongQuery) {
MPMediaItem *representativeItem = [arrayItem representativeItem]; // grab the next object from the collection
NSString *songName = [representativeItem valueForProperty: MPMediaItemPropertyTitle];
MPMediaItemArtwork *artWork = [representativeItem valueForProperty: MPMediaItemPropertyArtwork];
channelButtonTitles *aChannelButtonTitle = [[channelButtonTitles alloc] init]; // create an object to hold both the title and section number
aChannelButtonTitle.channelTitle = songName; // save the song name string in this object
aChannelButtonTitle.channelSubTitle = [representativeItem valueForProperty: MPMediaItemPropertyArtist]; // save the artists string in this object
aChannelButtonTitle.artwork = [artWork imageWithSize:CGSizeMake(30, 30)]; // save the artwork UIImage object
aChannelButtonTitle.persistentID = [representativeItem valueForProperty:MPMediaEntityPropertyPersistentID]; // save this unique number in case the user wants to play this
// Then determine which section number it belongs to.
// The collator will use the channelTitle property of the aChannelButtonTitle object to make this determination
NSInteger sect = [theCollation sectionForObject:aChannelButtonTitle collationStringSelector:@selector(channelTitle)];
aChannelButtonTitle.sectionNumber = sect; // Save the section number that this title string should be assigned to.
[tempTitles addObject:aChannelButtonTitle]; // Copy the channelButtonTitles object that contains the title and section number in the temp array
[aChannelButtonTitle release]; // Release the channelButtonTitles object
}
不幸的是,对于 2000 首歌曲,这需要将近 15 秒。分配 channelButtonTitle 对象的时间和 sectionForObject:collationStringSelector: 的执行时间都可以忽略不计。
似乎大部分时间都花在了获取 valueForProperty 的行上,尽管这行:
MPMediaItem *representativeItem = [arrayItem representativeItem];
需要 5 秒。
如何提高创建索引部分的性能(或至少提高用户等待某事发生的时间)?