gpt4 book ai didi

swift - 将图像存储在 swift 的 Core Data 中

转载 作者:行者123 更新时间:2023-11-30 11:25:03 27 4
gpt4 key购买 nike

我正在尝试将应用程序中的本地镜像保存到核心数据模型。我已经创建了实体并为图像创建了属性。但是当我运行该应用程序时,它崩溃并出现此错误,Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "image"; desired type = NSData; given type = UIImage; value = <UIImage:我保存图像的代码是,

 let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Saloon", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)

newUser.setValue(nameLbl.text, forKey: "name")
newUser.setValue(addressLbl.text, forKey: "address")
newUser.setValue(distanceLbl.text, forKey: "distance")
newUser.setValue(rating.text, forKey: "rating")
newUser.setValue(imageView.image, forKey: "image") as? UIImage
do {
try context.save()
print("saved")
} catch {
print("Failed saving")
}

这就是我获取图像的方式,

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Saloon")
//request.predicate = NSPredicate(format: "age = %@", "12")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {

print(data.value(forKey: "name") as! String)
let image: Data = data.value(forKey: "image")! as! Data
let decodedimage = UIImage(data: image)
imageView2.image = decodedimage
name2Lbl.text = data.value(forKey: "name") as? String
address2Lbl.text = data.value(forKey: "address") as? String
distance2Lbl.text = data.value(forKey: "distance") as? String
rating2Lbl.text = data.value(forKey: "rating") as? String
}

} catch {

print("Failed")
}

最佳答案

您无法将 UIImage 直接保存在 Core Data 中。相反,您必须将图像转换为 NSData (如错误消息中的“desired type = NSData”)。这是一个 UIImage 扩展:

extension UIImage {
func jpegData(withCompressionQuality quality: CGFloat) -> Data? {
return autoreleasepool(invoking: {() -> Data? in
return UIImageJPEGRepresentation(self, quality)
})
}
}

quality 是一个从 0.0 到 1.0 的值,后者代表 JPEG 压缩图像的最大质量。使用 autoreleasepool 有助于避免使用 UIImageJPEGRepresentation 时偶尔出现的内存泄漏问题。

然后您可以使用以下代码保存图像:

if let imageData = imageView.image .jpegData(withCompressionQuality: 1.0) {
newUser.setValue(imageData, forKey: "image")
}

顺便说一句,如果您需要的话,您还可以转换为 PNG 而不是无损的 JPEG。使用 UIImagePNGRepresentation 而不是 UIImageJPEGRepresentation

关于swift - 将图像存储在 swift 的 Core Data 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50833868/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com