ios - NSAttributedString 初始化抛出 NSRangeException

标签 ios swift nsattributedstring

我写了一个简单的扩展来解码 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/

相关文章:

ios - 当 iOS 上的 NSTextTab 不提供该选项时,如何在 iOS 上获得 Decimal Tab Stop?

ios - 原型(prototype)单元格从 JSON 获取不正确

ios - 将 Pan Gesture 与 Google VR Panorama 结合使用

ios - Facebook 移动应用安装广告跟踪安装路径

ios - iOS Swift 中简单的低延迟音频播放

ios - 制作模式以使用 NSRegularExpression

ios - 在 iOS 的 FCM 推送通知上启用默认声音

ios - 如何在 Swift 中使用 Arkit 在图像上播放托管视频?

ios - 将文本文件中的数据保存在数组和/或字典中