1

各セルの内容に大量の計算が必要な場合、UITableView をスムーズにスクロールし続ける最善の方法は何ですか? 例えば:

#define maxN 40

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return maxN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"CellIdentifier";

    UITableViewCell *cell = nil;
    cell = [tableView dequeueReusableCellWithIdentifier:cellId];

    //customization
    int row = indexPath.row;
    int fib = [self fib:row];

    cell.textLabel.text = [NSString stringWithFormat:@"%d", fib];

    return cell;
}

- (int)fib:(int)n
{
    return (n<=2 ? 1 : [self fib:n-1] + [self fib:n-2]);
}

これは、約 30 までの maxN で問題なく機能します。それより大きい値を使用すると、大きな数値の計算中にテーブル ビューが停止します。

ソリューションが非同期計算に関係していることは知っていますが、UI をスムーズに保つためにどのように設定しますか?

更新: 更新されたメソッドは次のとおりです。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"FibIdentifier";

    UITableViewCell *cell = nil;

    cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    [self configureCellAtIndexPath:indexPath];

    return cell;
}

-(void)configureCellAtIndexPath:(NSIndexPath *)indexPath {

    if ([self.fibResults objectAtIndex:indexPath.row] != [NSNull null]) {
        // apply cached result
        UITableViewCell *cell = [self.fibTable cellForRowAtIndexPath:indexPath];
        cell.textLabel.text = [NSString stringWithFormat:@"%d", [(NSNumber*)[self.fibResults objectAtIndex:indexPath.row] intValue]];

        return;
    }

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(void){
        NSInteger row = indexPath.row;
        int fib = [self fib:row];

        //cache the result
        [self.fibResults replaceObjectAtIndex:row withObject:[NSNumber numberWithInt:fib]];

        dispatch_async(dispatch_get_main_queue(), ^(void){
            [self.fibTable reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        });
    });
}

良いニュースは、テーブルがスムーズにスクロールすることです。悪いニュースは、セルが正しい 1、1、2、3、5、8 などの順序ではなく、ランダムな値で入力されることです。

4

1 に答える 1