title: How to encode an object that contains an attributed string to Data?
body: <p>I have an <code>NSDocument</code> subclass that contains a property of type <code>NSAttributedString</code> (among others). In order to enable persistence I need to override the following two methods:</p>
  
  <pre><code>override func data(ofType typeName: String) throws -&gt; Data {
      // Insert code here to write your document to data of the specified type, throwing an error in case of failure.
      // TO BE IMPLEMENTED...
  }
  
  override func read(from data: Data, ofType typeName: String) throws {
      // Insert code here to read your document from the given data of the specified type, throwing an error in case of failure.
      // TO BE IMPLEMENTED...
  }
  </code></pre>
  
  <p><strong>How do I encode my document to a <code>Data</code> object</strong> that I can return from the first method and then decode in the <code>read(from:ofType:)</code> method when needed?</p>
  
  <p>The <code>Codable</code> protocol and <code>NSKeyedArchiver</code> seem to be key components to achieve this. But when I try to encode the attributed string with it as follows:</p>
  
  <pre><code>convenience init(from decoder: Decoder) throws {
      self.init()
      do {
          let values = try decoder.container(keyedBy: CodingKeys.self)
          attributedString = values.decode(NSAttributedString.Type, forKey: .attributedString)
      } catch {
          // ...
      }
  }
  </code></pre>
  
  <p>I get the compiler error:</p>
  
  <blockquote>
    <p>No 'decode' candidates produce the expected contextual result type <code>NSAttributedString</code></p>
  </blockquote>
  
  <p>It seems like <code>NSAttributedString</code> doesn't support encoding/decoding but according to the documentation, it conforms to <code>NSSecureCoding</code> which inherits from <code>NSCoding</code>.</p>
  
  <p><strong>How can I encode the whole document with all its properties</strong>, including the attributed string?</p>
  
  <p>(Is there a simpler way than using <code>NSKeyedArchiver</code>?)</p>