将图像存储到CoreData - Swift [英] Storing images to CoreData - Swift
问题描述
在我的代码我设法保存一个textLabel与CoreData,但我似乎不能正确保存图像。我读了一些教程,我知道我必须将其转换为NSData。
>核心数据不是为了保存大的二进制文件,如图像。
code> let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true).first as! String
// self.fileName是您需要附加到基本目录的文件名。
let path = documentsDirectory.stringByAppendingPathComponent(self.fileName)
let success = data.writeToFile(path,atomically:true)
if!success {// handle error}
建议将 filename
编辑:还要注意,从ios8开始,持久化完整文件url无效,因为沙盒应用程序-id是动态生成的。您将需要根据需要动态获取 documentsDirectory
。
In my code I managed to save a textLabel with CoreData but I can't seem to properly save the image. I've read some tutorials and I know I have to convert it to NSData. But how do I do it?
Thanks in advance!
Core Data isn't meant to save big binary files like images. Use Document Directory in file system instead.
Here is sample code to achieve that.
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 }
It is recommended to save filename
part to core data along with other meta data associated with that image and retrieve from file system every time you need it.
edit: also note that from ios8 onwards, persisting full file url is invalid since sandboxed app-id is dynamically generated. You will need to obtain documentsDirectory
dynamically as needed.
这篇关于将图像存储到CoreData - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!