问题描述
我尝试在 macos 应用程序中解压已归档的 NSMutableAttributedString
,该应用程序是用 swift 编写的。我取回文本但没有任何属性。属性在导出的序列化中,但被 NSMutableAttributedString(coder: unarchiver)!
让我们深入了解:首先我创建一个 AttributedString 并用红色背景格式化一个单词:
let content = NSMutableAttributedString(string: "Dogs like to play with balls.")
content.addAttributes([NSAttributedString.Key.backgroundColor: NSColor.red],range: NSMakeRange(5,4))
然后我用 NSKeyedArchiver
序列化它:
let archiver = NSKeyedArchiver(requiringSecureCoding: false)
archiver.outputFormat = .xml
content.encode(with: archiver)
archiver.finishEncoding()
我将结果存储在一个变量中:
let serialisedData = archiver.encodedData
将其写回新的 NSMutableAttributedString
:
let unarchiver = try NSKeyedUnarchiver(forReadingFrom: serialisedData)
let restored = NSMutableAttributedString(coder: unarchiver)!
restored
AttributedString 没有任何形式。 :-(
有没有办法恢复属性?我可以看到颜色信息在 serialisedData
流中。我用 outputFormat
和 .xml
尝试了 .binary
,结果相同。
这是操场输出:
解决方法
明白了!
let archiver = try NSKeyedArchiver.archivedData(withRootObject: content,requiringSecureCoding: false)
和
let restored = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSMutableAttributedString.self,from: archiver)
呸!