实体的模型定义:
实体的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)
}