Primarily, I'm attempting to archive an NSDictionary with a UITouch in it. I keep receiving an error that says '-[UITouch encodeWithCoder:]: unrecognized selector sent to instance'.
If I remove the UITouch object from the dictionary, i don't receive the error.
I've been trying to figure it out myself, including searching through google for the past few hours, and have yet to find how to store a UITouch object in an NSDictionary.
here's the method I'm using:
- (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];
}
Any help would be greatly appreciated.
UITouch doesn't, by itself, conform to the <NSCoding>
protocol, since it doesn't have a trivial/obvious serialized representation (like a string or an array, which are basic data types). What you have to do is make it conform to this protocol by extending its class and deciding which properties should it serialize and in what kind of format. For example:
@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