将图像存储到 CoreData - Swift

Storing images to CoreData - Swift

在我的代码中,我设法用 CoreData 保存了一个 textLabel,但我似乎无法正确保存图像。我读过一些教程,我知道我必须将它转换为 NSData。但是我该怎么做呢?

提前致谢!

在这里你可以选择 JPEG,而对于 PNG,你只需使用 UIImagePNGRepresentation:

let image = UIImage(named: "YourImage")
let imageData = NSData(data: UIImageJPEGRepresentation(image, 1.0))
managedObject?.setValue(imageData, forKey: "YourKey")

一般来说,大型数据对象不会存储在数据库或 Core Data 中。而是将图像保存在 Document 目录(或子目录)中,并将文件名保存在 Core Data 中。

查看@Valentin 关于如何创建图像数据表示的答案。

func writeToFile(_ path: String, atomically atomically: Bool) -> Bool

保存

Core Data 并不是为了保存像图像这样的大二进制文件。请改用文件系统中的文档目录。

这是实现该目的的示例代码。

let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
// self.fileName is whatever the filename that you need to append to base directory here.
let path = documentsDirectory.stringByAppendingPathComponent(self.fileName)
let success = data.writeToFile(path, atomically: true)
if !success { // handle error }

建议将 filename 部分与与该图像关联的其他元数据一起保存到核心数据,并在每次需要时从文件系统中检索。

编辑:另请注意,从 ios8 开始,保留完整文件 url 无效,因为沙盒应用程序 ID 是动态生成的。您需要根据需要动态获取documentsDirectory

你不应该在核心数据中保存大数据,一位 Apple 工程师在上届 WWDC 上告诉我这个小技巧:

您可以使用 属性 "Allows external storage":

据我所知,通过这样做,您的图像将存储在文件系统中的某个位置,并且内部核心数据将 link 保存到文件系统中的图片。每次你要图片时,核心数据都会自动从文件系统中检索图像。

要将图像保存为 NSData,您可以执行以下操作:

let image = UIImage(named: "YourImage")
let imageData = NSData(data: UIImageJPEGRepresentation(image, 1.0))
managedObject?.setValue(imageData, forKey: "YourKey")

请记住 UIImageJPEGRepresentatio 中的 1.0 意味着您使用的是最佳质量,因此图像会又大又重:

The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).