views:

53

answers:

2

I have an entity in core data called Location. Inside this I have a few fields, such as date. But, I would also like to save a class object in it that I created called Annotation. What type of attribute would I use for this, since it is a custom class object that I created?

Location (object)
|__ Date
|__ Annotation (MKAnnotation protocol)
+1  A: 

it would be easier to add the class as a core data class then you could just have a relationship between the two classes as a one-to-one relation. you can however use the type binary data as an attribute type and store whatever data you want in there. ( i use this to store c structs sometimes ) You just need to use the NSData class to wrap your object and set the property.

Aran Mulholland
Ok, but since I would have to create attributes for Annotation, and the coordinate type is CLLocationCoordinate2D, how do I save that?
Nic Hubbard
+2  A: 

You have two options:

  1. If your Annotation class conforms to the NSCoding protocol (or if you're willing to write an NSValueTransformer to convert your custom class to an NSData instance, you can use a transformable attribute in your Core Data entity. Core Data will use the designated NSValueTransformer to automatically serialize/deserialize your Annotation instance for you.

  2. You can create an Annotation entity in your Core Data model. You'll have to write your own code to assign a CLLocationCoordinate2D to the entity. You would probably create a persistent backing using two doubles and then write setters/accessors for the CLLocationCoordinate2D.

The advantage of (1) is that it's easier (if your class conforms to NSCoding). The advantage of (2) is that you can query against the data within the entity, even if using SQLite persistent stores. If you use (1), the data is opaque to the SQLite query engine, so you won't be able to query against it with a SQLite backend.

Barry Wark
Personally I would go with number two.
Marcus S. Zarra
And @mzarra would definitely know. I would also personally recommend taking the long view and choosing option two.
Barry Wark