首先,我尝试归档一个包含UITouch的NSDictionary。我一直收到这样的错误:“-UITouch encodeWithCoder::unrecognized selector sent to instance”。
如果从字典中删除UITouch对象,则不会收到错误。
我自己一直在尝试解决这个问题,包括在过去的几个小时里搜索谷歌,但还没有找到如何在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];
}任何帮助都将不胜感激。
发布于 2013-01-15 14:03:00
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;
}
@endhttps://stackoverflow.com/questions/14331857
复制相似问题