我正在为表视图创建索引部分,以显示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秒。
我如何提高创建索引段的性能(或者至少改善用户等待某些事情发生的时间)?
由于缺乏任何其他建议,我发现可以通过将以下两行移动到tableView:cellForRowAtIndexPath:
将时间缩短一半 MPMediaItemArtwork *artWork = [representativeItem valueForProperty: MPMediaItemPropertyArtwork];
aChannelButtonTitle.artwork = [artWork imageWithSize:CGSizeMake(30, 30)]; // save the artwork UIImage object
aChannelButtonTitle.channelSubTitle = [representativeItem valueForProperty: MPMediaItemPropertyArtist]; // save the artists string in this object
因此,viewDidLoad仍然捕获歌曲标题(为了准备索引表的目的)和persistentID(使tableView:cellForRowAtIndexPath:能够轻松抓取插图和副标题)。它仍然需要一些改进,但它已经更好了。
一个更好的处理方法是使用NSOperationQueue和NSOperation。在这里可以找到一个与这个问题相关的很好的教程