码迷,mamicode.com
首页 > 编程语言 > 详细

Swift Core Data 图片存储与读取Demo

时间:2016-04-10 23:50:44      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

实体的模型定义:
技术分享

技术分享

实体的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地址

Swift Core Data 图片存储与读取Demo

标签:

原文地址:http://www.cnblogs.com/Free-Thinker/p/5376353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!