【问题标题】:iOS crash report "unexpected start state" exception?iOS崩溃报告“意外启动状态”异常?
【发布时间】:2018-04-03 12:45:12
【问题描述】:

我发现了几个崩溃报告,原因是 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;
}

崩溃报告如下所示:

【问题讨论】:

  • 看起来您正在加载的数据无效或损坏,或者无法解析。对带有错误处理程序的文档加载器的 try/catch 怎么样?
  • 非常感谢。我会试试看它是否起作用
  • 我也遇到了类似的问题,请问哪里可以解决?
  • 您的 html 有效吗?你是在主线程上调用这段代码吗?
  • 这里也一样。任何更新?我无法重现它。

标签: ios crash nsmutableattributedstring nsexception


【解决方案1】:

只需在后台线程中调用您的函数:

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
    });
});
【解决方案2】:

当您尝试使用除主线程之外的任何其他线程的 html 内容初始化 NSAttibutedString 时,会发生上述崩溃。

所以这里的解决方案是确保上面的NSAttributedString初始化总是从主线程调用

DispatchQueue.main.async {
    let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
    let htmlString = try? NSAttributedString(data: htmlData, options: options, documentAttributes: nil)
}

引用documentation

不应从后台线程调用 HTML 导入器(即,选项字典包含值为 html 的 documentType)。它将尝试与主线程同步,失败并超时。从主线程调用它是可行的(但如果 HTML 包含对外部资源的引用,仍然会超时,应该不惜一切代价避免这种情况)。 HTML 导入机制旨在实现诸如 markdown 之类的东西(即文本样式、颜色等),而不是用于一般的 HTML 导入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    相关资源
    最近更新 更多