【问题标题】:Cocoa: how to unarchive a NSMutableAttributedString with archived attributes?Cocoa:如何取消归档具有归档属性的 NSMutableAttributedString?
【发布时间】: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,结果相同。

这是 Playground 输出:

【问题讨论】:

    标签: swift cocoa nsattributedstring nsmutableattributedstring nskeyedunarchiver


    【解决方案1】:

    知道了!

    let archiver = try NSKeyedArchiver.archivedData(withRootObject: content, requiringSecureCoding: false)
    

    let restored = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSMutableAttributedString.self, from: archiver)
    

    哇!

    【讨论】:

      猜你喜欢
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多