Transformable Attributes in Core Data

The way I tend to use transformable attributes in Core Data is to just make use of the standard NSValueTransformer that gets used to encode/decode any object that conforms to the NSCoding Protocol, then in my NSManagedObject subclass, cast this to the type it’s expected to be (I use mogenerator to generate the subclasses by the way):

name it with suffix Object since it will have type id

name it with suffix Object since it will have type id

  @interface MyObject : _MyObject
  
  @property (nonatomic, strong) NSDictionary *metadata;
  
  @end

And then in the .m file, the accessors

  @implementation MyObject
  
  + (NSSet*)keyPathsForValuesAffectingMetadata
  {
      return [NSSet setWithObjects:@"metadataObject", nil];
  }
  
  - (void)setMetadata:(NSDictionary *)metadata
  {
      [self willChangeValueForKey:@"metadata"];
      self.metadataObject = metadata;
      [self didChangeValueForKey:@"metadata"];
  }
  
  - (NSDictionary*)metadata
  {
      [self willAccessValueForKey:@"metadata"];
      NSDictionary *metadata = (NSDictionary*)self.metadataObject;
      [self didAccessValueForKey:@"metadata"];
      return metadata;
  }
  
  // the rest of your implementation here...
  @end

Summary: Saving your custom object classes in CoreData is pretty straightforward when supporting the NSCoding protocol. It’s then easy to ensure typing by declaring properties that just wrap these Core Data attributes. This post is basically something of a recipe so I can remind myself later.

UPDATE:  See this post.  You can actually get mogenerator to set the data type for you and you don’t have to write these accessors at all.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s