Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift:将多个图像保存到核心数据_Swift_Core Data - Fatal编程技术网

Swift:将多个图像保存到核心数据

Swift:将多个图像保存到核心数据,swift,core-data,Swift,Core Data,我有一个配方实体,与RecipeImage有一对多关系。我遇到的问题是如何正确地保存多个图像。我要做的是,一旦我选择了图像,我就将它们存储在tempImageArray中。选择“完成”后,我尝试将tempImageArray中的图像转换为数据数组,因为Core data只接受图像作为二进制数据。然后我将recipe.images设置为该数据数组 目前,我只能保存一张照片,而不是多张 我想我已经接近解决方案了,但需要一些指导。非常感谢您的任何帮助 class ListDetailViewContr

我有一个配方实体,与RecipeImage有一对多关系。我遇到的问题是如何正确地保存多个图像。我要做的是,一旦我选择了图像,我就将它们存储在tempImageArray中。选择“完成”后,我尝试将tempImageArray中的图像转换为数据数组,因为Core data只接受图像作为二进制数据。然后我将recipe.images设置为该数据数组

目前,我只能保存一张照片,而不是多张

我想我已经接近解决方案了,但需要一些指导。非常感谢您的任何帮助

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