Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store custom class using CoreData

I have a class extending NSObject. It is consisting of a few float variables. I want to store this class in core data.

In the data model, It seems that the most probable option is to turn this class to a binary data in order to store it using CoreData.

Is this correct? If so, can someone please direct me to how I might store and retrieve my class using CoreData?

Thanks,

like image 748
qutaibah Avatar asked Oct 19 '11 17:10

qutaibah


People also ask

How do I use Core Data?

Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.

Where is Core Data stored?

The persistent store should be located in the AppData > Library > Application Support directory.

How do I store UIColor in Core Data?

In order to save a UIColor to core data you need to separate the red, blue, and green values. Then, within your creation code, fetch the RGB values and create a UIColor object with the fetched results.

Should I use Core Data?

The next time you need to store data, you should have a better idea of your options. Core Data is unnecessary for random pieces of unrelated data, but it's a perfect fit for a large, relational data set. The defaults system is ideal for small, random pieces of unrelated data, such as settings or the user's preferences.


1 Answers

A way that you can make your custom object transparently saved and loaded from Core Data is to use an NSValueTransformer. If you create an NSValueTransformer that can go from your class to NSData and vice versa, you can mark the attribute in your entity that corresponds to this class as being transformable. Core Data will then let you set and retrieve objects of this type when dealing with this attribute.

In my answer here I show code for how to do this with UIImage attributes, which are not supported natively by Core Data. To do something like this for your custom object, you'll need to make it NSCoding compliant and implement your own -encodeWithCoder: and -initWithCoder: methods to serialize it to an NSData instance for storage.

Apple has more documentation on this in the "Non-Standard Persistent Attributes" section of the Core Data Programming Guide, including an example that uses the Mac's NSColor class.

like image 69
Brad Larson Avatar answered Oct 11 '22 16:10

Brad Larson