ios - 异常没有被捕获

标签 ios swift nsattributedstring nsmutableattributedstring

Crashlytics 报告以下行有时抛出 NSInternalInconsistencyException:

let attrStr = try NSMutableAttributedString(
        data: modifiedFont.data(using: String.Encoding.unicode, 
        allowLossyConversion: true)!,
        options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
        documentAttributes: nil)

在这里,我对为什么发生这种情况( there's a 3 year old question about it )不像对捕获/处理此异常感兴趣。我尝试这样做:

do {
    let attrStr = try NSMutableAttributedString(
       data: modifiedFont.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
       options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
       documentAttributes: nil)

     self.attributedText = attrStr
} catch {
    self.attributedText = nil
    self.text = text.stripHTML()
}

...但是由于某种原因这不起作用 - 仍在报告异常。

我是否试图以正确的方式捕获它?到底能不能抓到呢?如果没有,我有什么选择?

最佳答案

Swift 将带有可空返回和尾随 NSError** 参数的 Objective-C 方法转换为在 Swift 中抛出的方法。但是,在 Objective-C 中,您也可以抛出异常。这些与 NSError 不同,Swift 不会捕获它们。事实上,Swift 中没有办法捕获它们。您必须编写一个 Objective-C 包装器来捕获异常并以 Swift 可以处理的某种方式将其传回。

您可以在 Apple 文档 Handling Cocoa Errors in Swift 中找到此内容在仅在 Objective-C 中处理异常部分。

事实证明您可以捕获它,但值得考虑是否应该捕获它(请参阅下面@Sulthan 的评论)。据我所知,大多数 Apple 框架都不是异常安全的(请参阅: Exceptions and the Cocoa Frameworks ),因此您不能只是捕获异常并继续,就像什么都没有发生一样。最好的选择是尽可能保存并尽快退出。另一个需要考虑的问题是,除非您重新抛出异常,否则 Crashlytics 等框架不会将其报告给您。因此,如果您确实决定捕获它,您应该记录它和/或重新抛出它,以便您知道它正在发生。

关于ios - 异常没有被捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56797850/

相关文章:

ios - 如何使用 xcassets 构建框架

ios - 将数组存储在 Realm 对象中

ios - 在 UITextView 中点击自定义 URL 链接时,委托(delegate)接收到 nil URL

swift - 对象映射器 + Realm + Alamofire

ios - 如何在 Xcode 中创建多部分表单或向导

ios - 子类化 NSMutableAttributedString 在初始化时返回 SIGABRT

swift - 如何在 swift 3 中使用 addAttribute 和 NSRANGE

ios - 如何将最后一个数组对象获取为int

ios - Swift 相当于 "[[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task)"

ios - 以编程方式更改其标题在 IB 中设置为属性的 UIButton 的标题