Chris McCall
Chris McCall

Reputation: 10397

How should I model key/value pairs in CoreData?

I am using CoreData to store the following class:

@interface TripSegment : NSManagedObject

@property (nonatomic, retain) NSString * details;
@property (nonatomic, retain) NSDate * endsOn;
@property (nonatomic, retain) NSString * segmentCategory;
@property (nonatomic, retain) NSDate * startsOn;
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * tripSegmentId;
@property (nonatomic, retain) ContextCard *contextCard;
@property (nonatomic, retain) Location *endsAt;
@property (nonatomic, retain) Location *startsAt;
@property (nonatomic, retain) Trip *trip;

@end

For some TripSegments, (flights, for instance), I have some additional data coming back, like confirmation number or seat assignments. I'd like to store these data in a flexible arrangement, so as I discover more useful stuff to present in the UI, I can include it in the service and start using it without having to migrate the model or deal with a complex class hierarchy.

How can I add key/values to an object persisted in a CoreData store? Or do I have to make specific classes to represent Flights or Hotel Stays and persist those separately with relationships?

Upvotes: 0

Views: 1357

Answers (2)

Daij-Djan
Daij-Djan

Reputation: 50089

As I noted on @rickerbh's answer, I'd go with option #2 IF you really need to add custom properties AT runtime -- which I dont think you need

I understood you just want to NOT have to migrate well... just make your mom into a momd and version it. as long as you just ADD or rename properties to the model, coredata can transparently migrate => no work for you :)

that's the cleanest IMO

Upvotes: 0

rickerbh
rickerbh

Reputation: 9911

As I see it you have a couple of options.

  1. You could add a Binary Data attribute to your TripSegment class, and use a NSKeyedArchiver to convert an NSDictionary storing the extra attributes to and from NSData
  2. You could implement your own generic key/value pair core data object, and have a one-many relationship between your TripSegment and that class.
  3. You could convert your extra data to and from JSON with NSJSONSerialization and store it as a String attribute on your TripSegment class.

I think it really depends on how you want to use the extra data you're getting back. If you need to be able to query the attributes independently of the TripSegment (e.g., get all seat assignments that have been allocated) then having a separate key/value style class is probably best. If you need the CD data to store binary information as part of the extra information received, then perhaps JSON serialization won't be the best option as the data size could blow out with the base64 conversion.

Upvotes: 1

Related Questions