实现异步计算 cell 高度并缓存,如何避免主线程等待布局完成?
解读
国内 iOS 面试中,「UITableView 高度计算」是高频考点。
- 早期做法是在主线程
-tableView:heightForRowAtIndexPath:里实时计算,数据量大或图文混排时掉帧明显。 - 后来出现「预缓存」思路:后台算好高度,主线程直接读取。但候选人常犯的错误是:
- 把 UIKit 控件(UILabel、YYText 等)直接丢到全局并发队列,触发 crash;
- 用信号量/同步派发到主线程等待结果,导致主线程卡死;
- 缓存 key 设计不合理,旋转屏幕后复用脏数据。
题目问「如何避免主线程等待布局完成」,核心考察两点:
a) 高度计算必须在后台线程完成;
b) 主线程不得同步等待,只能异步回调或立即返回「占位高度」。
知识点
- UIKit 线程模型:所有 UIKit 类(除少数文档标明外)必须在主线程使用。
- 文本排版安全 API:CoreText、NSAttributedString 的
boundingRectWithSize:options:context:以及 YYText/Texture 的离线排版接口,可在后台线程安全调用。 - 缓存设计:
- 双层缓存:内存 NSMutableDictionary + 磁盘(可选)。
- Key =
@"\(model.identifier)_\(width)_\(fontScale)_\(UIUserInterfaceSizeClass)",确保屏幕旋转、字体大小变化后重新计算。
- 并发控制:
- 同一 model 只触发一次计算,使用 NSLock 或 os_unfair_lock 保证线程安全。
- 使用 dispatch_semaphore 时绝不在主线程 wait,否则违背题目要求。
- 主线程零等待策略:
- 首次返回「估算高度」或「44 pt」占位;后台计算完成后通过
-[UITableView reloadRowsAtIndexPaths:withRowAnimation:]局部刷新。 - 也可以预加载:网络数据到达后立即在后台排队计算,cell 真正显示时高度已就绪。
- 首次返回「估算高度」或「44 pt」占位;后台计算完成后通过
- RunLoop/DisplayLink 防抖动:批量数据插入时,合并 reload 调用,避免主线程连续刷新。
答案
下面给出一份可直接落地的 Objective-C 代码,满足「后台计算 + 主线程不等待 + 线程安全缓存」。
// HeightCache.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface HeightCache : NSObject
+ (instancetype)shared;
- (CGFloat)heightForModel:(id)model
cellWidth:(CGFloat)width
completion:(void (^)(CGFloat finalHeight))completion;
@end
NS_ASSUME_NONNULL_END
// HeightCache.m
#import "HeightCache.h"
#import "FeedModel.h" // 业务数据模型
#import "FeedCellLayout.h" // 封装文本排版,内部使用 CoreText,线程安全
static NSString * const kHeightCacheKeyFmt = @"%@_%.2f_%.2f_%d";
static CGFloat const kEstimateHeight = 100.0;
@interface HeightCache ()
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSNumber *> *cache;
@property (nonatomic, strong) NSMutableSet<NSString *> *calculatingSet;
@property (nonatomic, strong) NSLock *lock;
@end
@implementation HeightCache
+ (instancetype)shared {
static HeightCache *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[HeightCache alloc] init];
});
return instance;
}
- (instancetype)init {
self = [super init];
if (self) {
_cache = [NSMutableDictionary dictionary];
_calculatingSet = [NSMutableSet set];
_lock = [[NSLock alloc] init];
}
return self;
}
- (CGFloat)heightForModel:(FeedModel *)model
cellWidth:(CGFloat)width
completion:(void (^)(CGFloat))completion {
// 1. 组装缓存 key
NSString *key = [NSString stringWithFormat:kHeightCacheKeyFmt,
model.identifier, width, model.fontSize, model.sizeClass];
// 2. 内存缓存命中直接回调
[self.lock lock];
NSNumber *cached = self.cache[key];
[self.lock unlock];
if (cached) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(cached.floatValue);
});
}
return cached.floatValue;
}
// 3. 防止重复计算:同一 key 只提交一次后台任务
[self.lock lock];
BOOL isCalculating = [self.calculatingSet containsObject:key];
if (!isCalculating) {
[self.calculatingSet addObject:key];
}
[self.lock unlock];
if (isCalculating) {
// 3.1 已在计算,本次返回估算高度,不回调
return kEstimateHeight;
}
// 3.2 真正提交后台计算
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 使用 CoreText/YYText 离线排版,全程不访问 UIKit
FeedCellLayout *layout = [[FeedCellLayout alloc] initWithModel:model maxWidth:width];
CGFloat height = MAX(layout.totalHeight, 44.0);
// 4. 写缓存
[self.lock lock];
self.cache[key] = @(height);
[self.calculatingSet removeObject:key];
[self.lock unlock];
// 5. 主线程回调,让调用方 reload 对应行
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(height);
});
}
});
// 6. 主线程立即返回估算高度,绝不等待
return kEstimateHeight;
}
@end
使用方式(在 UITableViewDelegate 内):
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
FeedModel *model = self.dataList[indexPath.row];
CGFloat width = CGRectGetWidth(tableView.bounds);
__weak typeof(self) weakSelf = self;
[[HeightCache shared] heightForModel:model
cellWidth:width
completion:^(CGFloat finalHeight) {
// 计算完成,刷新这一行;若高度无变化 reload 会自动优化为 noop
[weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationNone];
}];
// 立即返回,主线程不等待
return [[HeightCache shared] heightForModel:model cellWidth:width completion:nil];
}
关键点回顾
- 全程无 dispatch_semaphore wait,主线程绝不阻塞。
- 后台只使用 CoreText/YYText,不触碰 UIKit。
- 相同 model+width 只计算一次,锁粒度小。
- 首次用估算高度,用户几乎无感知;后续局部刷新,帧率稳定 60 fps。
拓展思考
- 屏幕旋转/字体放大:
在UIContentSizeCategoryDidChangeNotification与viewWillTransitionToSize:里清空对应 sizeClass 的缓存,避免“高度错位”。 - 磁盘缓存:
把cache字典归档到 Library/Caches/feed_height,下次冷启直接 mmap 读取,减少二次排版。注意版本号升级时淘汰旧缓存。 - 增量更新:
对于图文混排中的远程图片,可在图片下载完成后仅更新「图片高度」部分,再重新累加文本高度,避免整段重排。 - SwiftUI 与 Texture:
若团队已迁移至 SwiftUI,可改用.task+AsyncImage的异步布局;若用 Texture(AsyncDisplayKit),其calculateLayoutThatFits:默认就是后台并发,思路与上述方案一致,但框架已封装好缓存。 - 性能验证:
使用 Instruments 的 Time Profiler 检查主线程是否出现semaphore_wait_trap;使用 FPS 面板确保滚动全程 55–60 帧,才算真正达到「零等待」标准。