Cocoa: how to unarchive a NSMutableAttributedString with archived attributes?

135 Views Asked by At

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.

Here is the Playground output: Playground

1

There are 1 best solutions below

0
On

Got it!

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

and

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

Doh!