How to store CGColor in Core Data?

1.5k Views Asked by At

I'm wanting to store/save CGColor in Core Data.

Currently, I'm storing colours with floats for red, blue, green, etc.

I'm needing to store the topColor and bottomColor as they are used in a very simple gradient image for an avatar's background.

My current version is very cumbersome and requires me to store the RGB values as floats. It is cumbersome because I have to pass the RGB values manually; rather than say passing the actual CGColor and then breaking up/grabbing the RGB values.

Anyway, my question is how to store cgcolor in core data and would welcome any support, help or guidance on the best way to store cgcolor values in core data.

Thank you.

// My current version follows...
-(void)createColorScheme:(NSManagedObjectContext *)context withName:(NSString *)tColorName 
         withTopColorRed:(float)tColorRed 
        withTopColorBlue:(float)tColorBlue 
       withTopColorGreen:(float)tColorGreen
      withBottomColorRed:(float)bColorRed 
    withBottomColorGreen:(float)bColorGreen 
     withBottomColorBlue:(float)bColorBlue
{
    NSError *error;

    ColorScheme *c = [NSEntityDescription insertNewObjectForEntityForName:@"ColorScheme" inManagedObjectContext:context];
    [c setName:@"Red"];
    [c setTaken:[NSNumber numberWithInt:0]];
    [c setTopColorRed:[NSNumber numberWithFloat:tColorRed]];
    [c setTopColorBlue:[NSNumber numberWithFloat:tColorBlue]];
    [c setTopColorGreen:[NSNumber numberWithFloat:tColorGreen]];
    [c setBottomColorRed:[NSNumber numberWithFloat:bColorRed]];
    [c setBottomColorGreen:[NSNumber numberWithFloat:bColorGreen]];
    [c setBottomColorBlue:[NSNumber numberWithFloat:bColorBlue]];

    if (! [context save:&error] )
    {
        NSLog(@"Unresolved Core Data Save error %@, %@", error, [error userInfo]);
        exit(-1);
    }

    c = nil;
}
2

There are 2 best solutions below

1
On

You might need to use coredata's non standard persistant attributes for saving CGColor. This is apple's documentation for that. This SO link explains it a bit..

0
On

I decided to just store floats and retrieve them as and when required. I know its not the best way, but it seems to work.