0

首先,我试图归档一个带有 UITouch 的 NSDictionary。我不断收到一条错误消息,上面写着“-[UITouch encodeWithCoder:]: unrecognized selector sent to instance”。

如果我从字典中删除 UITouch 对象,我不会收到错误消息。

我一直试图自己弄清楚,包括过去几个小时通过谷歌搜索,但还没有找到如何将 UITouch 对象存储在 NSDictionary 中。

这是我正在使用的方法:

- (void)sendMoveWithTouch:(id)touch andTouchesType:(TouchesType)touchesType {
     MessageMove message;
     message.message.messageType = kMessageTypeMove;
     message.touchesType = touchesType;
     NSData *messageData = [NSData dataWithBytes:&message length:sizeof(MessageMove)];

     NSMutableData *data = [[NSMutableData alloc] init];
     NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

     [archiver encodeObject:@{@"message" : messageData, @"touch": touch} forKey:@"touchesDict"]; //RECEIVE ERROR HERE. If I remove the UITouch object, everything passes correctly

     [archiver finishEncoding];

     [self sendData:data];
}

任何帮助将不胜感激。

4

1 回答 1

1

UITouch 本身并不符合<NSCoding>协议,因为它没有简单/明显的序列化表示(如字符串或数组,它们是基本数据类型)。你要做的是通过扩展它的类并决定它应该序列化哪些属性以及以什么样的格式来使其符合这个协议。例如:

@implementation UITouch (Serializable)

- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:@([self locationInView:self.view].x) forKey:@"locationX"];
    [coder encodeObject:@([self locationInView:self.view].y) forKey:@"locationY"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init]) {
        // actually, I couldn't come up with anything useful here
        // UITouch doesn't have any properties that could be set
        // to a default value in a meaningful way
        // there's a reason UITouch doesn't conform to NSCoding...
        // probably you should redesign your code!
    }
    return self;
}

@end
于 2013-01-15T06:03:00.293 回答