NSData变量未保存到CoreData

时间:2019-03-27 16:33:56

标签: swift core-data

我正在尝试转换用户从相机胶卷导入的图像,将图像转换为NSData并将其作为二进制数据存储在CoreData中。我已经设法将其转换为二进制文件并打印出来,但是我没有将值存储到核心数据中。我已经设法将字符串和其他值存储到实体的不同属性,但是无论出于何种原因,二进制数据都无法正常工作。

func savingData(savingImage: UIImage){


        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext

        let userEntity = NSEntityDescription.entity(forEntityName: "Image", in: managedContext)!

        let data = savingImage.pngData()! as NSData


        if idLabel.text != "" {

            let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
            user.setValue(idLabel.text, forKeyPath: "id")
            user.setValue(descriptionText.text, forKey: "imgdescription")
            user.setValue(confidenceLabel.text, forKey: "confidence")
            user.setValue(data, forKey: "binary")


            do {
                try managedContext.save()
                dataSaved.text = "Your answers have been saved! Click Home to return."


            } catch let error as NSError {
                print("Could not save. \(error), \(error.userInfo)")
                dataSaved.text="Error!"
            }
        }
    }
}

这是我用于存储数据的代码。所有值都保存到核心数据中,并且可以在下一类中检索这些值。

我已经检查了所有连接,三次检查了实体和属性的命名,但仍然无法正常工作。

有人有什么主意吗?

编辑:属性“二进制”作为“二进制数据”存储在核心数据中

func retrieveData() {

        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

        let managedContext = appDelegate.persistentContainer.viewContext

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Image")

        fetchRequest.fetchLimit = 1
        fetchRequest.predicate = NSPredicate(format: "id = %@", valueSelected)
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "id", ascending: false)]

        do {
            let result = try managedContext.fetch(fetchRequest)
            for data in result as! [NSManagedObject] {
                idText.text = data.value(forKey:"id") as? String
                descriptionText.text = data.value(forKey:"imgdescription") as? String
                confidenceText.text = data.value(forKey:"confidence") as? String
                photoView = data.value(forKey:"binary") as? UIImageView
            }

        } catch {

            print("Nothing found.")
        }
    }

这是我在另一堂课中的称呼方式

1 个答案:

答案 0 :(得分:1)

主要问题是您将数据强制转换为UIImageView

retrieveData方法中,您必须根据数据创建一个UIImage并将图像分配给图像视图

基本上有一些改进可以提高安全性。

  • 声明具有本机Swift类型(例如NSManaged)的Data对象,并尽可能避免使用可选参数。
  • 使用始终点表示法访问CoreData属性,而不是易于出错的KVC
  • 如果要访问特定实体,请始终使用特定的NSFetchRequest

func savingData(savingImage: UIImage){

        // don't guard AppDelegate, the app won't even launch if it was missing so this line would be never reached
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedContext = appDelegate.persistentContainer.viewContext

        let imageEntity = NSEntityDescription.entity(forEntityName: "Image", in: managedContext)!

        let data = savingImage.pngData()!


        if !idLabel.text.isEmpty {

            let image = NSManagedObject(entity: imageEntity, insertInto: managedContext) as! Image
            image.id = idLabel.text
            image.imgdescription = descriptionText.text
            image.confidence = confidenceLabel.text
            image.binary = data

            do {
                try managedContext.save()
                dataSaved.text = "Your answers have been saved! Click Home to return."

            } catch let error as NSError {
                print("Could not save. \(error), \(error.userInfo)")
                dataSaved.text="Error!"
            }
        }
    }
}

func retrieveData() {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<Image>(entityName: "Image")
    fetchRequest.fetchLimit = 1
    fetchRequest.predicate = NSPredicate(format: "id = %@", valueSelected)
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)]

    do {
        let images = try managedContext.fetch(fetchRequest)
        for image in images {
            idText.text = image.id
            descriptionText.text = image.imgdescription
            confidenceText.text = image.confidence
            if let imageData = image.binary {
               photoView.image = UIImage(data: imageData)
            }
        }

    } catch {
        print("Nothing found.", error)
    }
}