Swift:将多个图像保存到核心数据
我有一个配方实体,与RecipeImage有一对多关系。我遇到的问题是如何正确地保存多个图像。我要做的是,一旦我选择了图像,我就将它们存储在tempImageArray中。选择“完成”后,我尝试将tempImageArray中的图像转换为数据数组,因为Core data只接受图像作为二进制数据。然后我将recipe.images设置为该数据数组 目前,我只能保存一张照片,而不是多张 我想我已经接近解决方案了,但需要一些指导。非常感谢您的任何帮助Swift:将多个图像保存到核心数据,swift,core-data,Swift,Core Data,我有一个配方实体,与RecipeImage有一对多关系。我遇到的问题是如何正确地保存多个图像。我要做的是,一旦我选择了图像,我就将它们存储在tempImageArray中。选择“完成”后,我尝试将tempImageArray中的图像转换为数据数组,因为Core data只接受图像作为二进制数据。然后我将recipe.images设置为该数据数组 目前,我只能保存一张照片,而不是多张 我想我已经接近解决方案了,但需要一些指导。非常感谢您的任何帮助 class ListDetailViewContr
class ListDetailViewController: UITableViewController {
var recipeToEdit: Recipe?
var recipeImages = [RecipeImage]()
//image collection
var tempImageArray = [UIImage]()
private func createRecipe() {
let context = CoreDataManager.shared.persistentContainer.viewContext
let recipe = NSEntityDescription.insertNewObject(forEntityName: "Recipe", into: context) as! Recipe
recipe.setValue(textField.text, forKey: "name")
let image = NSEntityDescription.insertNewObject(forEntityName: "RecipeImage", into: context) as! RecipeImage
for i in tempImageArray {
image.imageData = i.jpegData(compressionQuality: 0.8)
recipeImages.append(image)
}
recipe.images?.setValue(recipeImages, forKey: "images")
image.recipe = recipe
do {
try context.save()
//Perform save
navigationController?.popViewController(animated: true)
self.delegate?.didAddRecipe(recipe: recipe)
} catch let saveErr {
print("Failed to save recipe", saveErr)
}
}
您正在更新循环内相同图像的
imageData
。尝试通过在循环中移动let image=NSEntityDescription…
为每个图像创建一个新实体。这样做时,我将无法访问“image.recipe=recipe”。当我把它放到循环中时,我得到一个错误。如果你有关系b/w image和recipe,你不必同时设置recipe.images
和image.recipe
。从配方
到图像
创建到多个
关系,从图像
到配方
创建到一个
关系,并重新生成模型类。谢谢,这解决了我的问题!我所要做的就是删除recipe.images.setValue