将 HTML 字符串转换为 NSAttributedString 时 运行 存档崩溃

Crash on running Archive when converting HTML string to NSAttributedString

Xcode 7.3Swift 2.2

在 swift 文件中,我有一个字符串扩展,可将 HTML 文本转换为 NSAttributedString。

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
        return html
    }
}

我是这样用的

let HTMLstr = "<p><b>hello</b> world</p>"
if let attrString = HTMLstr.htmlAttributedString() {
    // do something here
}

它在我的 phone 和模拟器中工作正常,但是当我 存档 它时,它会导致使用上面的代码崩溃。我认为问题出在dataUsingEncoding。使用 archived 应用程序时会崩溃的任何想法。

编辑

我已经包含了崩溃日志的 header:

Incident Identifier: 90C74E49-4C65-4556-B82D-6748437BB5BA
CrashReporter Key:   4fb0e685f950c6cdecf7132b26f38ff54e013348
Hardware Model:      iPhone7,1
Process:             AppName [7813]
Path:                /private/var/containers/Bundle/Application/1EE7C00E-7600-4D72-839D-8AEA834903B8/AppName.app/AppName
Identifier:          uk.co.skymook.AppName
Version:             1 (2.0)
Code Type:           ARM-64 (Native)
Parent Process:      launchd [1]

Date/Time:           2016-08-13 12:16:08.08 +0100
Launch Time:         2016-08-13 12:15:33.33 +0100
OS Version:          iOS 9.3.2 (13F69)
Report Version:      105

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x2000000000000000
Triggered by Thread:  0

Filtered syslog:
None found

长答案:解决方案的调试非常缓慢。我必须检查导致崩溃的所有代码,并确保对可选项进行了正确的检查。所以我不得不屏蔽掉很多代码,构建存档并将其缩小到一些功能。然后我不得不屏蔽掉每一行代码,构建存档,直到我发现是什么导致它崩溃。应用程序中有数百行代码,而且归档需要时间,这并不容易。最后,一个可选值在它为 nil 时被解包。请记住,它在模拟器中解包 OK,在调试中 运行ning,我很惊讶地发现了这个问题。

简答:这是一个用 nil 解包的可选项,与上面的代码无关。归档应用程序时,内存处理方式略有不同,编译器可以通过所有代码有效性测试。

吸取的教训是为生产归档,并在整个开发过程中phone定期运行它。