IOS开发IOS性能优化

NSAttributedString NSHTMLTextDoc

2019-04-29  本文已影响0人  那个推车的人

使用NSAttributedString初始化 html 文本时(NSHTMLTextDocumentType)会导致主线程卡死。这应该是苹果的解析 html 文本的一个 bug。

NSAttributedString.init(data:(string?.data(using:.unicode))!,options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

按照苹果文档的说法,上述代码不可以运行在后台线程(background thread),其次,它会出现 time out 超时,运行在主线程会造成线程卡死。

所以最正确做法应该是通过 global queue进行初始化,然后将结果丢回主线程刷新 ui。

DispatchQueue.global().async {
    let text = try? NSAttributedString(data: contentToDisplay.data(using: .unicode)!,
                            options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes:nil)
    DispatchQueue.main.async {
        strongSelf.contentLabel.attributedText = text
    }
}

ios - NSAttributedString initWithData and NSHTMLTextDocumentType crash if not on main thread - Stack Overflow

上一篇 下一篇

猜你喜欢

热点阅读