将图像存储到CoreData - Swift [英] Storing images to CoreData - Swift

查看:107
本文介绍了将图像存储到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆