Swift Core Data 圖片儲存與讀取Demo

來源:互聯網
上載者:User

標籤:

實體的模型定義:

實體的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

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.