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,
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.
The persistent store should be located in the AppData > Library > Application Support directory.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With