title: Saving NSData from CoreData Managed Object in a CloudKit Asset
body: <p>I have a small image stored as <code>NSData</code> in a CoreData Managed Object that I need to save in a <code>CloudKit</code> record as <code>CKAsset</code>.</p>
  
  <p>I was hoping to simply cast the <code>NSData</code> from the managed object like this:</p>
  
  <pre><code>myCKRecord["document"] = myCDRecord.document as! CKAsset
  </code></pre>
  
  <p>Unfortunately, this cast does not work, so I have made a work-around by writing a file with the <code>NSData</code>, and using the file to initialise the <code>CKAsset</code>.</p>
  
  <pre><code>class myManagedObject: NSManagedObject {
  
      @NSManaged var image: NSData?
      @NSManaged var name: String
  
  
  func createCloudKitAsset(myCDRecord : myManagedObject) -&gt; CKRecord
  
      let myCKRecordID = CKRecordID(recordName: myCDRecord.name)
      let myCKRecord = CKRecord(recordType: "myCKType", recordID: myCKRecordID)
  
      let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
      let localURL =  NSURL.fileURLWithPath(dirPaths.first + "/" + recordName)
      let fileManager = NSFileManager.defaultManager()
      fileManager.createFileAtPath(localURL.path!, contents: myCDRecord.image, attributes: nil)
  
      myCKRecord["image"] = CKAsset(fileURL: localURL)
     ...
  }
  </code></pre>
  
  <p>This works, but is untidy, and I still have the temporary file to be cleaned up after the CK record is saved.</p>
  
  <p>Hopefully, someone can show me a better way to do this.
  Thanks</p>