UITableView在tableView:cellForRowAtIndexPath:回调函数中创建NSDateFormatter对象导致滑动卡顿

创建NSDateFormatter对象是比较耗时的操作,特别是在tableView滑动过程中大量创建NSDateFormmatter对象将会导致tableView滑动明显卡顿。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellI = @"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellI];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellI];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Item %ld", indexPath.row];
    
    for (int i = 0; i < 30; i++) {
        NSString *timeStr = @"20171111 11:11:11";
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMdd HH:mm:ss"];
        [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        
        NSDate *timeDate = [formatter dateFromString:timeStr];
        double time = [timeDate timeIntervalSince1970];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%f", time];
    }
    
    return cell;
}

上面的代码在tableView的滑动过程中FPS只有30帧左右,看起来有明显的卡顿。


解决办法:

我们只需要创建一个NSDateFormatter对象,在tableView滑动的过程中复用这个NSDateFormatter对象。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellI = @"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellI];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellI];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Item %ld", indexPath.row];
    
    for (int i = 0; i < 30; i++) {
        NSString *timeStr = @"20171111 11:11:11";
        
        static NSDateFormatter *formatter = nil;
        if (formatter == nil) {
            formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyyMMdd HH:mm:ss"];
            [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        }
        
        NSDate *timeDate = [formatter dateFromString:timeStr];
        double time = [timeDate timeIntervalSince1970];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%f", time];
    }
    
    return cell;
}

代码改成上面这种后tableView在滑动过程中FPS也一直保持60帧,滑动非常顺畅。

UITableView Custom Cell very slow

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容