我写了一个简单的扩展来解码 html 实体:
extension String {
func htmlDecode() -> String {
if let encodedData = self.data(using: String.Encoding.unicode) {
let attributedString = try! NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.unicode], documentAttributes: nil)
return attributedString.string
}
return self
}
}
现在它在 if let attributedString …
行抛出错误:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 4 beyond bounds [0 .. 2]'
self
不是 nil 之类的,只是一个像这样的 String
:
self = (String) "...über 25'000 Franken..."
这个奇怪的NSArray
异常是从哪里来的?
最佳答案
黑暗中的一枪:你确保初始化发生在主线程上吗?
我遇到了完全相同的问题。我注意到在我的例子中,异常发生在可重现的条件下(UICollectionViewController 中的动画),但我无法找到真正的原因。我最好的猜测是它是一个框架错误,所以我也建议你提交雷达。
我最终将 HTML 格式的字符串预渲染到缓存(又名数组)中,然后根据需要从中加载 NSAttributedStrings。
请注意,尽管此解决方案可能不适合您的用例,因为我一次只需要处理有限数量的格式化字符串,因此知道提前呈现它们的费用。
关于ios - NSAttributedString 初始化抛出 NSRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29483703/