tom*_*der 25 crash nsexception ios nsmutableattributedstring
我找到了几个崩溃报告的原因unexpected start state.我的代码看起来像这样:
NSRange range = [content rangeOfString:@"<html>"];
if (range.location != NSNotFound) {
NSString *htmlStr = [content substringFromIndex:range.location];
NSAttributedString *attStr = [[NSAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
return attStr.string;
}
Run Code Online (Sandbox Code Playgroud)
崩溃报告如下所示:
NSAttibutedString当您尝试使用主线程以外的任何其他线程的 html 内容初始化 a 时,就会发生上述崩溃。
所以这里的解决方案是确保上述NSAttributedString初始化始终从主线程调用。
DispatchQueue.main.async {
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
let htmlString = try? NSAttributedString(data: htmlData, options: options, documentAttributes: nil)
}
Run Code Online (Sandbox Code Playgroud)
引用文档:
HTML 导入器不应从后台线程调用(即选项字典包含值为 html 的 documentType)。它会尝试与主线程同步,失败并超时。从主线程调用它是可行的(但如果 HTML 包含对外部资源的引用,仍然可能会超时,应该不惜一切代价避免这种情况)。HTML 导入机制旨在实现类似 markdown 的功能(即文本样式、颜色等),而不是用于一般的 HTML 导入。
只需在后台线程中调用您的函数:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
// here, call your function
dispatch_async(dispatch_get_main_queue(), ^{
// do updates on main thread
});
});
Run Code Online (Sandbox Code Playgroud)