IOS/Objective-C: Convert standard UIColor to CGColor

858 Views Asked by At

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

3

There are 3 best solutions below

7
Jabson On BEST ANSWER

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];
2
LS_ On

Replace

circleColor = [[myColor] CGColor];//does not work

with

circleColor = myColor.CGColor;

EDIT

If you haven't saved your UIColor in NSUSerDefaults check this answer for an example on how to correctly store and retrieve it.

0
Abhishek Mitra On

I think you haven't create myColor object in this line.

UIColor* myColor = [[NSUserDefaults standardUserDefaults] objectForKey:myColor];
struct CGColor* circleColor = nil;

First initialise that object then assign on that object with your user defaults then proceed accordingly.