Swift Core Data 图片存储与读取Demo

前端之家收集整理的这篇文章主要介绍了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地址

原文链接:/swift/327447.html

猜你在找的Swift相关文章