Bannings的专栏

self.life("iOS developer")

Swift Core Data 图片存储与读取Demo

实体的模型定义:
这里写图片描述

这里写图片描述

实体的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://blog.csdn.net/zhangao0086/article/details/44499405
文章标签: demo Coredata ios swift
个人分类: iOS开发 Swift开发
上一篇Swift Nullability and Objective-C
下一篇TestFlight Beta 备忘
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭