title: How To Optimize Storage Of NSAttributedString In Swift Using Data And Codable?
body: <p>I am trying to optimize storage space when saving the contents of a <code>NSTextView</code>, namely its <code>NSTextStorage</code> property, itself a <code>NSAttributedString</code>.</p>
  
  <p>Saving it as <code>Data</code>, for example using the <code>rtfd(from:documentAttributes:)</code> method, and as part of a <code>Codable</code> structure, results in a very large string, much larger than the content itself especially when inserting an image into the <code>NSTextView</code>. For example, inserting a 200K image will result in a 5MB JSON  file.</p>
  
  <p>Side note: It is even worse when the <code>Data</code> object is encoded directly rather than as a property of the encoded object, as it is encoded in the form of an array of small integers rather than an arbitrary string. I am not sure why, though I was able to prevent this by inserting the <code>Data</code> into a simple wrapper structure.</p>
  
  <p>Strangely, compressing the actual JSON file using ZIP still results in a 4MB file, merely a 20% gain, so it is unclear to me how a 200K image could turn into such a massive, hardly compressable encoded string.</p>
  
  <p>I would like to figure out what is the proper way to efficiently store <code>NSAttributedString</code> using the <code>Codable</code> protocol. Any hint or advice is much appreciated.</p>
  
  <p>I am also wondering whether there is a valid binary encoding option for <code>Codable</code>.</p>