I am using a custom NSValueTransformer to store color information in my master data store. The conversion between Transformable data and the UIColor instance works fine after the color data is already in the store (i.e., after the application has been launched and has already been completed). However, when I first run the application and load these values (from a text file), they get stuck like NSCFStrings.
In this line of code, “attributes” has a dictionary that has keys, which are the names and values of the NSManagedObject attributes, which are the expected values for these attributes. In my color example, a pair of key values "color": "1,1,1,0,5"
[object setValue:[attributes valueForKey:attribute] forKey:attribute];
The value for "color" will now remain a string in this instance until it is converted through my NSValueTransformer and then converted again to UIColor when the application starts again.
I could do the same conversion that I do in NSValueTransformer, but this is in a utility class that I wrote that could theoretically be used for any transformer. I also thought about finding a way to get all newly created NSManagedObject instances from memory, thereby forcing the conversion to go through, but it just looks like a hack.
Note. This "hacking" works for me and allows me to continue, but still feels ugly. Use the NSManagedObjectContext reset method if you have similar problems / finding a "just work" solution.
Any ideas?
( , " Core Data NSValueTransformer?", )
NSValueTransformer
@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