编码NSAttributedString会引发错误

Chr*_*ris 0 objective-c nsattributedstring nskeyedarchiver nscoder

基于对此问题的接受答案,我编写了以下代码:

NSData* somedata;
somedata=[NSKeyedArchiver archivedDataWithRootObject:ts];
Run Code Online (Sandbox Code Playgroud)

其中ts是一个NSAttributedString,它填充了一些文本和一些属性(在本例中为颜色).

当我执行此代码时,我收到此错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x6eb5b90'
Run Code Online (Sandbox Code Playgroud)

我是NSCoder竞技场的新手,但上述问题的答案使我觉得这就是我所要做的.是吗?我错过了什么?


编辑:

在这种情况下,无法识别的选择器被发送到NSAttributedString中的颜色属性.当我像这样初始化字符串时:

NSAttributedString *ts = [[NSAttributedString alloc] initWithString:text attributes:self.currentAttributeDictionary];
Run Code Online (Sandbox Code Playgroud)

字典就像这样构建:

self.currentAttributeDictionary=[NSDictionary dictionaryWithObjectsAndKeys:
                                 [self.currentColor CGColor],(NSString*)kCTForegroundColorAttributeName,
                                 nil];
Run Code Online (Sandbox Code Playgroud)

字典的NSLog产生了这个:

New dictionary is: {
CTForegroundColor = "<CGColor 0x6eb5b90> [<CGColorSpace 0x6e968c0> (kCGColorSpaceDeviceRGB)] ( 1 1 0 1 )";}
Run Code Online (Sandbox Code Playgroud)

上面的CGColor的地址与错误消息中的地址匹配.

Con*_*ltz 6

虽然UIColor符合NSCoding,但它(不像大多数这样的类)不是免费的桥接CGColorRef.您的字典正在尝试编码其内容,并且CGColorRef不知道如何编码自己.

假设您不想编码UIColor(因为这些声音类似于Core Text属性),您将不得不处理CGColorRef自己的序列化.例如,请参阅此问题以获得一些有用的想法.

应该注意的是,顺便说一句,因为我不知道归档数据的去向,如果你想取消归档OS X上的数据,颜色再次成为AppKit/UIKit级别的头疼:NSColor并且UIColor不直接兼容,所以你仍然需要通过CGColorRef,适当地存储颜色空间信息.