gpt4 book ai didi

ios - 线程安全属性字符串高度计算

转载 作者:行者123 更新时间:2023-11-29 02:22:56 26 4
gpt4 key购买 nike

如何以线程安全的方式计算属性字符串的高度?我正在为一个可能非常复杂的布局预先计算单元格高度,并且不想在执行计算时阻塞主线程。这是我正在做的事情(为了便于阅读而进行了简化):

// 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();
}

});
});
}

最佳答案

苹果 does not recommend从主线程调用上述方法,解释如下:

The HTML importer should not be called from a background thread (that is, the options dictionary includes NSDocumentTypeDocumentAttribute with a value of NSHTMLTextDocumentType). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.

如果有人知道任何替代方法来处理确定后台线程的高度,我仍然很高兴!

关于ios - 线程安全属性字符串高度计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27914766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com