【问题标题】:Swift-3 error: '-[_SwiftValue unsignedIntegerValue]: unrecognized selectorSwift-3 错误:'-[_SwiftValue unsignedIntegerValue]:无法识别的选择器
【发布时间】:2017-01-31 06:55:17
【问题描述】:

以下代码与旧 swift 完美配合。这是字符串的扩展

func stringByConvertingHTML() -> String {
    let newString = replacingOccurrences(of: "\n", with: "<br>")
    if let encodedData = newString.data(using: String.Encoding.utf8) {
        let attributedOptions : [String: AnyObject] = [
            NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
            NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject
        ]
        do {
            let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) //Crash here
            return attributedString.string
        } catch {
            return self
        }
    }
    return self
}

但是在 swift 3 中它会崩溃说

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

谁能告诉我需要做什么?

【问题讨论】:

    标签: ios xcode exception swift3


    【解决方案1】:

    我遇到了同样的问题:

    let attributedOptions : [String: AnyObject] = [
                NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
                NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject
            ]
    

    这里的String.Encoding.utf8 类型检查失败。使用NSNumber(value: String.Encoding.utf8.rawValue)

    【讨论】:

    • 谢谢它工作正常。但它会是NSNumber(value: String.Encoding.utf8.rawValue)
    • 救命稻草! (PS:还需要 NSNumber( .. ) 才能工作,您能否更新答案以包含它?)
    • 你应该只需要String.Encoding.utf8.rawValue,因为当一个Swift字典被传递给一个期望NSDictionary的函数时,Swift会自动将Ints和UInts转换成NSNumbers。尽管这需要将 swift 字典设为 [String: Any] 数组。另请参阅 this Swift 博客条目。
    • 有时我会收到 NSRangeException,对此有任何解决方案
    • 奇怪!但确实,枚举应该作为 rawValue 发送。我认为它会在未来的版本中得到修复。
    【解决方案2】:

    在 Swift3 中,不再需要强制转换为 AnyObject,也不需要 NSNumber。

    let attrs: [String: Any] = [
                NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
            ]
    

    【讨论】:

    • 我会说这是最干净的方法。
    【解决方案3】:

    这篇文章拯救了我的一天。迁移到 Swift 3 后,String.Encoding.utf8String.Encoding.utf8.rawValue 的小改动修复了此处报告的陷阱。

    原线:

    ...
        options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
                  NSCharacterEncodingDocumentAttribute: String.Encoding.utf8],
    ...
    

    改为

    options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
              NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
    

    .rawValue 添加到末尾...

    【讨论】:

    • 永远不会从错误提示中猜到解决方案是在末尾添加 .rawValue。非常感谢!
    猜你喜欢
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多