我正在尝试将用户生成的图像保存到核心数据。如果我对图像进行编程,则代码可以正常工作。但是当用户选择图像时,我收到错误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")
}