编码NSAttributedString引发错误 [英] Encoding NSAttributedString Throws Error

查看:171
本文介绍了编码NSAttributedString引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Based on the accepted answer to this question I wrote the following code:

NSData* somedata;
somedata=[NSKeyedArchiver archivedDataWithRootObject:ts];

其中ts是一个NSAttributedString,其中填充了一些文本和一些属性(在这种情况下为颜色).

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'

我是NSCoder领域的新手,但是对上述问题的回答似乎是我要做的所有事情.是吗?我错过了什么吗?

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?

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

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];

字典的构建方式如下:

self.currentAttributeDictionary=[NSDictionary dictionaryWithObjectsAndKeys:
                                 [self.currentColor CGColor],(NSString*)kCTForegroundColorAttributeName,
                                 nil];

然后,字典的NSLog产生以下结果:

And an NSLog of the dictionary yields this:

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

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

The address of the CGColor, above, matches the address in the error message.

推荐答案

虽然UIColor符合NSCoding,但(不同于大多数此类)不是免费电话桥接到.您的字典正在尝试对其内容进行编码,而CGColorRef不知道如何对自身进行编码.

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.

假设您不想对UIColor进行编码(因为这些听起来像Core Text属性),那么您将不得不自己处理CGColorRef的序列化.有关一些有用的想法,请参见例如此问题.

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.

请注意,顺便说一句,因为我不知道归档数据的去向,所以如果您要取消归档OS X上的数据,那么颜色再次成为AppKit/UIKit级别的麻烦:NSColorUIColor不直接兼容,因此您仍然需要通过CGColorRef,适当地存储色彩空间信息.

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.

这篇关于编码NSAttributedString引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆