Swift Core Data 图片存储与读取Demo

前端之家收集整理的这篇文章主要介绍了Swift Core Data 图片存储与读取Demo前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

实体的模型定义:

实体的class定义:

@objc(ImageEntity)
@H_301_12@class ImageEntity: NSManagedObject {
    @NSManaged var imageData: NSData
}

存储:

@IBAction func saveImageToCoreData() {
    @H_301_12@let @H_301_12@delegate = UIApplication.sharedApplication().@H_301_12@delegate @H_301_12@as AppDelegate
    @H_301_12@let context = @H_301_12@delegate.managedObjectContext

    @H_301_12@let imageData = UIImagePNGRepresentation(UIImage(named: "image"))

    @H_301_12@let imageEntity = NSEntityDescription.entityForName("ImageEntity",inManagedObjectContext: context!)
    @H_301_12@let image = ImageEntity(entity: imageEntity!,insertIntoManagedObjectContext: context!)
    image.imageData = imageData

    @H_301_12@var error: NSError?
    @H_301_12@if context!.save(&error) == @H_301_12@false {
        println("Failed: \(error!.localizedDescription)")
    }
}

读取:

@IBAction func loadImageFromCoreData() {
    @H_301_12@let @H_301_12@delegate = UIApplication.sharedApplication().@H_301_12@delegate @H_301_12@as AppDelegate
    @H_301_12@let context = @H_301_12@delegate.managedObjectContext

    @H_301_12@let request = NSFetchRequest(entityName: "ImageEntity")
    @H_301_12@var error: NSError?
    @H_301_12@let imageEntities = context?.executeFetchRequest(request,error: &error)

    @H_301_12@let imageEntity = imageEntities?.first! @H_301_12@as ImageEntity
    self.imageView.image = UIImage(data: imageEntity.imageData)
}

Demo地址

猜你在找的Swift相关文章