How to store an image in core data

前端 未结 7 1244
你的背包
你的背包 2020-11-27 09:59

I\'m new to iOS. I\'ve been trying to make an application that will store an image captured from the camera into CoreData. I now know how to store data like

7条回答
  •  天涯浪人
    2020-11-27 10:31

    It is possible to store images in Core Data as UIImage. Although this is not considered to be good practice as Databases are not meant for storing files. We don't use core data to store the images directly instead we use the file path to where the image data is stored on your phone.

    Anyways, the best method I found out while developing a side-project is demonstrated below

    1. Set the entity codeGen to Manual/None

    2. Select the attribute you want to be of Image type and choose transformable as it's type

    3. Enter Custom class identifier as UIImage

    4. Go to editor and select Create NSManagedObject Subclass

    5. The Process will create 2 swift files depending on the number of your entities(I only had 1 entity). Now, select the + CoreDataProperties.swift file and import UIKit

    If, on clicking Jump to Definition for the @NSManaged public var UIImage definition your work is done.

    Perform actions on the entities just like you would and you will be able to fetch, save, edit the image attribute by down-casting ?.value(forKey: "") as? UIImage.

    I had to use the entity as NSManagedObject type and was for some reason not able to access the image directly from the created subclass.

提交回复
热议问题