title: Using an NSValueTransformer to set values of an NSManagedObject instance
body: <p>I am using a custom NSValueTransformer to store color information in my Core Data store. The transformation between Transformable data and a UIColor instance works great once the color data is in the store already (ie once the app has been run and quit once already). However when I first run the app and am loading in these values (from a text file) they "stuck" as NSCFStrings.</p>
  
  <p>In this line of code "attributes" is a dictionary has keys which are NSManagedObject attribute names and values that are the expected values for those attributes. In my color example the key value pair is "color":"1,1,1,0.5"</p>
  
  <pre><code>[object setValue:[attributes valueForKey:attribute] forKey:attribute];
  </code></pre>
  
  <p>The value for "color" will now remain a string in this instance until it's get transformed via my NSValueTransformer and then retransformed into a UIColor when the app gets run again.</p>
  
  <p>I could just do the same transform here that I'm doing in the NSValueTransformer, but this is in a utility class I wrote that could theoretically be used for any transformer. I also thought of finding a way to get all newly created NSManagedObject instances out fo memory thereby forcing the transformation to go through, but that just seems like a hack. </p>
  
  <p>Note: This "hack" works for me and let's me continue, but still feels ugly. Use NSManagedObjectContext's reset method if you're having similar problems / looking for a "just work" solution.</p>
  
  <p>Any ideas?</p>
  
  <p>(I have a hunch this is similar to " <a href="https://stackoverflow.com/questions/1598600/why-is-my-transformable-core-data-attribute-not-using-my-custom-nsvaluetransforme">Why is my transformable Core Data attribute not using my custom NSValueTransformer?</a> " but outside of the title our problems seem to be different)</p>
  
  <p>Here is my NSValueTransformer</p>
  
  <pre><code>@implementation UIColorRGBValueTransformer
  
  + (Class)transformedValueClass
  {
      return [NSData class];
  }
  
  + (BOOL)allowsReverseTransformation
  {
      return YES;
  }
  
  - (id)transformedValue:(id)value
  {
      return [value dataUsingEncoding:NSUTF8StringEncoding];
  }
  
  - (id)reverseTransformedValue:(id)value
  {
      NSString *colorAsString = [[[NSString alloc] initWithData:value encoding:NSUTF8StringEncoding] autorelease];
      NSArray *components = [colorAsString componentsSeparatedByString:@","];
      CGFloat r = [[components objectAtIndex:0] floatValue];
      CGFloat g = [[components objectAtIndex:1] floatValue];
      CGFloat b = [[components objectAtIndex:2] floatValue];
      CGFloat a = [[components objectAtIndex:3] floatValue];
      return [UIColor colorWithRed:r green:g blue:b alpha:a];
  
      return nil;
  }
  
  @end
  </code></pre>