NSAttributedString初始化抛出NSRangeException

Fab*_*oni 9 nsattributedstring ios swift

我写了一个简单的扩展来解码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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在它在行上抛出一个错误if let attributedString …:

***由于未捕获的异常'NSRangeException'终止应用程序,原因:'*** - [__ NSArrayM objectAtIndex:]:索引4超出边界[0 .. 2]'

self不是零什么的,只是一个String像这样的:

self = (String) "...über 25'000 Franken..."

这种奇怪的NSArray例外来自哪里?

Fab*_*oni -1

我刚刚用另一个错误运行了这个错误:

*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[_SwiftValue unsignedIntegerValue]:无法识别的选择器发送到实例 0x60000024b790”

并发现这段代码有一个严重的bug:

我将String.Encoding.unicode一个 Swift 值传递给 Objective-C 方法,导致应用程序崩溃。使用后String.Encoding.unicode.rawValue崩溃消失:

extension String {
    func htmlDecode() -> String {
        if let encodedData = self.data(using: String.Encoding.unicode) {
            if let attributedString = try? NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.unicode.rawValue], documentAttributes: nil) {
                return attributedString.string
            }
        }
        return self
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Bonan 你能详细说明一下你的具体用例吗?查看崩溃堆栈跟踪,我的问题似乎与 UICollectionView 动画内容密切相关,但我不能确定。我的解决方法(请参阅我的答案)是提前而不是按需进行转换。 (2认同)
  • 我仍然在 Swift 3 的答案中遇到代码错误(由于未捕获的异常“NSRangeException”而终止应用程序,原因:“*** -[__NSArrayM objectAtIndexedSubscript:]:索引 0 超出空数组的范围”) (2认同)