title: Converting image to NSData to save in core data
body: <p>I'm trying to store an image in <code>core data</code>.</p>
  
  <p>My <code>core data</code> properties file requires the image to be in <code>NSData</code> :</p>
  
  <pre><code> import Foundation
   import CoreData
  
   extension Item {
  
      @nonobjc public class func fetchRequest() -&gt; NSFetchRequest&lt;TaskItem&gt; {
      return NSFetchRequest&lt;TaskItem&gt;(entityName: "Item");
      }
  
      @NSManaged public var itemImage: NSData?
  }
  </code></pre>
  
  <p>However when I'm trying to save to <code>core data</code> using:</p>
  
  <pre><code>    @IBAction func saveBtnTapped(_ sender: AnyObject) {
  
  
          let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
  
          let item = Item(context: context)
  
          let imageData: NSData = UIImageJPEGRepresentation(taskImage.image!, 0.2) 
  
          item.itemImage = imageData
  
          (UIApplication.shared.delegate as! AppDelegate).saveContext()
  
         }
         navigationController?.popViewController(animated: true)
      }
  </code></pre>
  
  <p>I get the following error:</p>
  
  <pre><code>Cannot convert value of type 'Data?' to specified type 'NSData'
  </code></pre>
  
  <p>I thought I was doing it right, but it's not working for me. Could someone please give me an idea of how to fix it?</p>
  
  <p>Thanks in advance.</p>