我有一个名为Task
的实体,其中taskImage
是二进制数据的属性。我有以下
@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)