Улучшите время загрузки секционированного UITableView - PullRequest
0 голосов
/ 25 сентября 2011

Я отображаю UITableView модально, но для его появления требуется около двух секунд, ниже приведен код, который задерживает переход.

ModalViewController.m:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // get all songs from iTunes library
    MPMediaQuery *songQuery = [MPMediaQuery songsQuery];
    // put the songs into an array 
    self.songsArray = [songQuery items];
    // create a sectioned array where songs are sectioned by title
    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;
}

Приведенный выше код работает нормально, но он медленно загружает модальное представление в первый раз, есть ли лучший способ сделать это?Спасибо.

1 Ответ

1 голос
/ 25 сентября 2011

Да: не делай этого в -viewDidLoad.Лучшее место было бы в контроллере вида -init или -initWithNibNamed:bundle: или где-либо еще, и на заднем плане.Пример:

- (id)init
{
    self = [super init];
    if(self)
    {
        // ...

        dispatch_async(dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAULT, 0), ^{
            // since it's not on the main thread, you need to create your own autorelease pool to prevent leaks
            NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

            MPMediaQuery *songQuery = [MPMediaQuery songsQuery];
            self.songsArray = [songQuery items];            
            self.sectionedSongsArray = [self partitionObjects:self.songsArray collationStringSelector:@selector(title)];

            // UI calls have to be on the main thread, so we go back to that here
            dispatch_async(dispatch_get_main_queue(), ^{
                if([self isViewLoaded])
                {
                    [self.tableView reloadData];
                }
            });

            // this releases any objects that got autoreleased earlier in the block
            [pool release];
        });
    }

    return self;
}

Ваш метод -tableView:numberOfRowsInSection:, конечно, теперь должен проверить, является ли sectionedSongsArray не-nil, и в этом случае вернуть 0 (или 1, если вы хотите отобразить ячейку «загрузки», что вам, вероятно, следует).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...