# Swift Core Data 图片存储与读取Demo
实体的模型定义:
![](https://box.kancloud.cn/2016-01-18_569ca44d7bb0a.jpg)
![](https://box.kancloud.cn/2016-01-18_569ca44d8bc95.jpg)
实体的class定义:
~~~
@objc(ImageEntity)
class ImageEntity: NSManagedObject {
@NSManaged var imageData: NSData
}
~~~
存储:
~~~
@IBAction func saveImageToCoreData() {
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
let context = delegate.managedObjectContext
let imageData = UIImagePNGRepresentation(UIImage(named: "image"))
let imageEntity = NSEntityDescription.entityForName("ImageEntity", inManagedObjectContext: context!)
let image = ImageEntity(entity: imageEntity!, insertIntoManagedObjectContext: context!)
image.imageData = imageData
var error: NSError?
if context!.save(&error) == false {
println("failed: \(error!.localizedDescription)")
}
}
~~~
读取:
~~~
@IBAction func loadImageFromCoreData() {
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
let context = delegate.managedObjectContext
let request = NSFetchRequest(entityName: "ImageEntity")
var error: NSError?
let imageEntities = context?.executeFetchRequest(request, error: &error)
let imageEntity = imageEntities?.first! as ImageEntity
self.imageView.image = UIImage(data: imageEntity.imageData)
}
~~~
## [Demo地址](https://github.com/zhangao0086/CoreDataSaveImageDemo)
- 前言
- iOS 自定义页面的切换动画与交互动画 By Swift
- Swift 元组(Tuples)介绍
- Swift 可选值(Optional Values)介绍
- Swift Switch介绍
- Swift 值类型和引用类型
- Swift 柯里化(Currying)
- iOS GCD使用指南
- iOS8 Core Image In Swift:自动改善图像以及内置滤镜的使用
- 让Xcode自动更新Build版本
- Swift 全功能的绘图板开发
- Swift Nullability and Objective-C
- Swift Core Data 图片存储与读取Demo
- Swift 绘图板功能完善以及终极优化
- 如何设计一个 iOS 控件?(iOS 控件完全解析)