首先,我正在尝试将包含UITouch的NSDictionary存档。我一直收到一个错误,指出“-[UITouch encodeWithCoder:]:无法识别的选择器发送到实例”。

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

我一直在试图弄清楚自己的身份,包括在过去几个小时内通过Google搜索,但还没有找到如何在NSDictionary中存储UITouch对象的方法。

这是我使用的方法:

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


任何帮助将不胜感激。

最佳答案

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

10-04 19:57