I try to unarchive an archived NSMutableAttributedString
in a macos-app, written in swift. I get back the text but without any attributes. The attributes are in the exported serialisation but it is ignored by NSMutableAttributedString(coder: unarchiver)!
Let's dive in: first I create a AttributedString and format one word with a red background:
let content = NSMutableAttributedString(string: "Dogs like to play with balls.")
content.addAttributes([NSAttributedString.Key.backgroundColor: NSColor.red], range: NSMakeRange(5, 4))
Then I serialise it with a NSKeyedArchiver
:
let archiver = NSKeyedArchiver(requiringSecureCoding: false)
archiver.outputFormat = .xml
content.encode(with: archiver)
archiver.finishEncoding()
I stored the result in a variable:
let serialisedData = archiver.encodedData
to write it back into a new NSMutableAttributedString
:
let unarchiver = try NSKeyedUnarchiver(forReadingFrom: serialisedData)
let restored = NSMutableAttributedString(coder: unarchiver)!
the restored
AttributedString does not have any formations. :-(
Is there is a way to restore the attributes? I can see that the color information is in the serialisedData
stream. I tried outputFormat
with .xml
and .binary
with same results.
Got it!
and
Doh!