我正在尝试将imageview保存为二进制数据的核心数据。在我的函数中,我已经保存了一个字符串,它可以正常工作。但是,当我尝试使用(theTitle2)做完全相同的事情时,它不起作用。我在下面的问题中也有cdhandler类,这是应用程序deleagate中保存的内容。我认为我要做的就是以某种方式将图像视图转换为uiimage然后保存它。
func enterData() {
let appDeldeaget = UIApplication.shared.delegate as! AppDelegate
let context = appDeldeaget.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let theTitle = NSManagedObject(entity: entity!, insertInto: context)
theTitle.setValue(enter.text, forKey: "userName")
let theTitle2 = NSManagedObject(entity: entity!, insertInto: context)
theTitle2.setValue(imageV.image, forKey: "pit")
do {
try context.save()
itemName.append(theTitle)
}
catch { }
//
}
应用代理
class cdHandler: NSObject {
class func saveObject(userName: String) -> Bool {
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let managedObject = NSManagedObject(entity: entity!, insertInto: context)
managedObject.setValue(userName, forKey: "userName")
managedObject.setValue(userName, forKey: "pit")
do {
try context.save()
return true
} catch {
return false
}
}
}
答案 0 :(得分:0)
如果要在核心数据中保存图像,请将图像转换为数据然后存储。喜欢
let data = imageV.image?.jpegData(compressionQuality: 1) //image in JPEG format
or
let data = imageV.image?.pngData() // image in PNG format
theTitle2.setValue(data, forKey: "pit")