Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an image in Core Data?

Just a guess: I make an attribute and make it's type "binary". But in the end, how would I use that? I guess there is an NSData behind the scenes? So that attribute actually takes an NSData?

like image 247
dontWatchMyProfile Avatar asked Jun 06 '10 17:06

dontWatchMyProfile


People also ask

How do I save an image in Core Data in Swift?

Name it img and make sure the attribute type is Binary Data, then click on the img attribute and go to Data Model Inspector. Check the box Allows External Storage. By checking this box, Core Data saves a reference to the data which will make for faster access.

How do I save an image in UserDefaults swift 5?

We ask the FileManager class for the URL of the Documents directory and append the name of the file, landscape. png, to the URL. Writing a Data object to disk is a throwing operation so we wrap it in a do-catch statement. If the operation is successful, we store the URL in the user's defaults database.

How does Core Data save data?

Most interactions with Core Data will occur through an instance of NSManagedObjectContext : the portal through which our app will create new entities, save changes, and fetch from the store. The persistent container comes with a NSManagedObjectContext as one of its built-in properties.


2 Answers

This question has been asked a number of times and the answer is a bit more complex.

When it comes to binary data you should determine how to store it based on the expected size of data you are going to be working with. The rule is:

  • Less than 100K;store as a binary property in your main table
  • Less than 1M; store as a binary property in a ancillary table to avoid over fetching
  • Greater than 1M; store on disk and store its file path in the Core Data table.

In addition, when you are storing images, it is recommended to store them in a standard format such as JPG or PNG. By using the transformable property type you can actually have your subclass give the appearance of accessing the UIImage class when the actual store is a PNG representation. I go into this in detail in the bog post on Cocoa Is My Girlfriend.

Update

The reason behind storing > 1M binary data on disk is because of the cache. The NSPersistentStoreCoordinator will keep a cache of data so that when your app asks for the "next" object it doesn't need to go back out to disk. This cache works really well. However it is small, very small on iOS. If you pull in a big piece of binary data you can easily blow out that entire cache and your entire app suffers greatly.

like image 196
Marcus S. Zarra Avatar answered Oct 21 '22 03:10

Marcus S. Zarra


That's correct, use binary which is represented as a NSdata object, then u can use uiimages imageWithData class method in order to retrieve your images.

like image 28
Daniel Avatar answered Oct 21 '22 02:10

Daniel