10

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,

qutaibah
  • 313
  • 1
  • 4
  • 11

3 Answers3

10

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.

Community
  • 1
  • 1
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
0

My first suggestion is to create an entity that stores these values as the object types you are using are supported in Core Data.

If you are going to change this model often/dont want to deal with data migration then you can always set property of the object to being transformable as its type in the core data model. Then ensure that your class implements the NSCoding protocol, once you do this then it should work fine.

Reedy
  • 1,866
  • 2
  • 20
  • 23
0

I would suggest creating a new Entity in Core Data, modeling those fields in new entity, and refactoring your code to use the new custom subclass of Managed Object.

logancautrell
  • 8,762
  • 3
  • 39
  • 50