iosobjective-ccgcolor

IOS/Objective-C: Convert standard UIColor to CGColor


I have set a color in an NSUserDefault in another class and and now want to convert it to a CGColor for display. I can convert an actual UIColor to a CGColor. But I'm having trouble converting a UIColor stored in a variable to a CGColor

UIColor* myColor = [[NSUserDefaults standardUserDefaults] objectForKey:myColor];
struct CGColor* circleColor = nil;
circleColor=[[UIColor greenColor]CGColor];//this works 
circleColor=[[myColor] CGColor];//does not work
circleColor=[myColor CGColor];//does not work

Can anyone suggest the right way to do this?

Note: I did not save a cgcolor in the userdefaults due to the need to bridge


Solution

  • You can't save UIColor object in NSUserDefaults directly.

    try to archive object to get data and save the data like this:

    UIColor *color = [UIColor redColor];
    NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
    [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"ColorKey"];
    

    And when you need the color firstly you should get NSData object from User Defaults and then create UIColor object like this

    NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"ColorKey"];
    UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];