Based on the accepted answer to this question I wrote the following code:
NSData* somedata;
somedata=[NSKeyedArchiver archivedDataWithRootObject:ts];
where ts is an NSAttributedString that is populated with some text and some attributes (colors, in this case).
When I execute this code, I receive this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x6eb5b90'
I'm new to the NSCoder arena, but the answer to the aforementioned question made it seem like this is all I have to do. Is it? Did I miss something?
EDIT:
The unrecognized selector in this case is being sent to a color attribute in the NSAttributedString. When I initialize the string like so:
NSAttributedString *ts = [[NSAttributedString alloc] initWithString:text attributes:self.currentAttributeDictionary];
The dictionary is built like so:
self.currentAttributeDictionary=[NSDictionary dictionaryWithObjectsAndKeys:
[self.currentColor CGColor],(NSString*)kCTForegroundColorAttributeName,
nil];
And an NSLog of the dictionary yields this:
New dictionary is: {
CTForegroundColor = "<CGColor 0x6eb5b90> [<CGColorSpace 0x6e968c0> (kCGColorSpaceDeviceRGB)] ( 1 1 0 1 )";}
The address of the CGColor, above, matches the address in the error message.
While UIColor
conforms to NSCoding
, it is (unlike most such classes) not toll-free bridged to CGColorRef
. Your dictionary is attempting to encode its contents, and CGColorRef
doesn't know how to encode itself.
Presuming that you don't want to encode a UIColor
instead (since these sound like Core Text attributes), you are going to have to handle serialization of the CGColorRef
yourself. See, for example, this question for some useful thoughts.
It should be noted, btw, since I don't know where the archived data is going, that if you want to unarchive the data on OS X that colors again become a headache at the AppKit/UIKit level: NSColor
and UIColor
are not directly compatible, so you would still need to go via CGColorRef
, stashing the color space information as appropriate.