【问题标题】:Save UITouch to NSDictionary将 UITouch 保存到 NSDictionary
【发布时间】:2013-01-15 05:51:41
【问题描述】:

首先,我正在尝试归档一个带有 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];
}

任何帮助将不胜感激。

【问题讨论】:

    标签: ios objective-c xcode nsdictionary uitouch


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 2014-04-16
      相关资源
      最近更新 更多