Kamil
Kamil

Reputation: 1097

ios - Converting UIColor to NSData gives error when color has a pattern

I want to convert a UIColor object to NSData so that I can save it using NSUserDefaults. The following code works:

NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:[UIColor redColor]];

However, if I create a color using an image as follows:

UIImage *img  = [UIImage imageNamed:@"mypattern.png"];
UIColor *c = [UIColor colorWithPatternImage:img];
NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:c];

I get the following error: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only RGBA or White color spaces are supported in this situation.'

Any help?

Upvotes: 0

Views: 431

Answers (1)

Saad Chaudhry
Saad Chaudhry

Reputation: 1412

Here the need is to understand the difference between simple UIColor conversion and a color extracted of colorWithPatternImageconversion to NSData.

You can only serialise certain UIColor objects.

Instead of serialising the UIColor, you need to store the image that the pattern was created from. Do this in your encodeWithCoder:

Then, in your initWithCoder: you should dearchive the image and create a new UIColor from that Have a look at this link (preferred) and this link .

When you create your UIColor color = [UIColor colorWithPatternImage:selectedImage], also set the associated object on the color [color setAssociatedObject:selectedImage].

Upvotes: 1

Related Questions