【发布时间】:2021-04-22 20:04:43
【问题描述】:
我尝试在一个用 swift 编写的 macos-app 中解压缩归档的 NSMutableAttributedString。我取回文本但没有任何属性。属性在导出的序列化中,但被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 流中。我用.xml 和.binary 尝试了outputFormat,结果相同。
【问题讨论】:
标签: swift cocoa nsattributedstring nsmutableattributedstring nskeyedunarchiver