首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将UITouch保存到NSDictionary

将UITouch保存到NSDictionary
EN

Stack Overflow用户
提问于 2013-01-15 13:51:41
回答 1查看 537关注 0票数 0

首先,我尝试归档一个包含UITouch的NSDictionary。我一直收到这样的错误:“-UITouch encodeWithCoder::unrecognized selector sent to instance”。

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

我自己一直在尝试解决这个问题,包括在过去的几个小时里搜索谷歌,但还没有找到如何在NSDictionary中存储UITouch对象的方法。

下面是我使用的方法:

代码语言:javascript
复制
- (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];
}

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-15 14:03:00

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

代码语言:javascript
复制
@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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14331857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档