如何以线程安全的方式计算属性字符串的高度?我正在为可能非常复杂的布局预先计算单元格高度,并且不想在执行计算时阻塞主线程。这是我正在做的事情(为可读性而简化):
// pre-calculate layout information
- (void)performHeightCalculations:(MFBlock)completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
// ...
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
// Height calculation for attributed string
// Crash: EXC_BAD_ACCESS 0xbadbeef
label.attributedText = [[NSAttributedString alloc]
initWithData:HTMLString dataUsingEncoding:NSUTF8StringEncoding]
options:options
documentAttributes:nil
error: &err];
height += [label sizeThatFits:CGSizeMake(contentWidth, CGFLOAT_MAX)].height;
// ...
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion();
}
});
});
}
Apple 不建议从主线程中调用上述方法,解释如下:
不应从后台线程调用 HTML 导入程序(即 是,选项字典包括 NSDocumentTypeDocumentAttribute 值为 NSHTMLTextDocumentType)。它将尝试同步 使用主线程、失败和超时。从主调用它 线程工作(但如果 HTML 包含引用,仍可能超时 外部资源,应不惜一切代价避免)。该目录 导入机制旨在实现类似降价的东西 (即文本样式、颜色等),不适用于常规 HTML 进口。
如果有人知道任何替代方法来处理确定背景线程的高度,我仍然敞开心扉!