2016-09-30 112 views
0

我有一個名爲Task的實體,其中taskImage是二進制數據的屬性。我有以下如何將圖像從collectionviewcell存儲到核心數據

@IBOutlet weak var collectionView: UICollectionView! 
var imageSelected = [UIImage]() 

然後,我有收集觀點如下

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

     return self.imageSelected.count 

    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ 
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) 
       as! EditCollectionViewCell 

      cell.imageView?.image = imageSelected[(indexPath as NSIndexPath).row] 
      cell.layer.borderColor = UIColor.white.cgColor 
      cell.layer.borderWidth = 3 

       return cell 
     } 

現在我要當按下保存欄按鈕項圖像保存到核心數據如下

@IBAction func saveBtnPressed(_ sender: AnyObject) { 

    if #available(iOS 10.0, *) { 
     let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 

     let task = Task(context: context) 

     task.taskDesc = taskText.text! 
//task.taskImage = UIImagePNGRepresentation(cell.imageView?.image) 

    } else { 
     // Fallback on earlier versions 
    } 

我得到taskImage的錯誤,任何有關存儲圖像的幫助將不勝感激。

+0

檢索它您能詳細的錯誤? –

回答

1

我的代碼存儲圖像核心數據

let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
let context:NSManagedObjectContext = appDel.managedObjectContext 

let newContact = NSEntityDescription.insertNewObjectForEntityForName("Contact", inManagedObjectContext: context) 
let imageData:NSData = UIImageJPEGRepresentation(imgViewPhoto.image!, 1)! 
newContact.setValue(imageData, forKey: "imageData") 

和coredata

let imageData:NSData = contact.valueForKey("imageData") as! NSData 
imgViewPhoto.image = UIImage(data: imageData, scale: 1) 
+0

我相信你的imgViewPhoto是UIImageview類型的。但我的圖像是收集視圖的一部分,所以上述不適用於我 – Coder221

+0

因此,當您按下保存按鈕時,將保存哪個圖像? –

+0

我想從圖像陣列中保存選定的圖像集合視圖 – Coder221