首页 > 解决方案 > 将用户生成的图像保存到核心数据时出现运行时错误(Swift5)

问题描述

我正在尝试将用户生成的图像保存到核心数据。如果我对图像进行编程,则代码可以正常工作。但是当用户选择图像时,我收到错误Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value at jx = drawPlace.image!. 我只想解决这个问题,代码就可以工作了。仅将包装保存到核心数据中没有任何问题。

    var jx = UIImage()
var drawPlace = UIImageView()
func save() {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

    let managedContext = appDelegate.persistentContainer.viewContext

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

    let item = NSManagedObject(entity: entity, insertInto: managedContext)


    jx = drawPlace.image!
    if let data = jx.pngData() {
        item.setValue(data, forKey: "image")
    }

标签: core-dataimageviewoptionalswift5binary-image

解决方案


推荐阅读