【问题标题】:Why does the following code return incorrect values from NSData?为什么以下代码从 NSData 返回不正确的值?
【发布时间】:2013-11-22 02:05:01
【问题描述】:

我需要以 NSData 的形式通过网络发送数据。由于格式只能在运行时确定(例如:消息类型、对象数量等、对象类型),我使用以下代码来打包/解包 NSData

打包:

NSMutableData *data = [NSMutableData dataWithCapacity:0];
unsigned int _state = 66;
[data appendBytes:&state length:sizeof(state)];

打开包装(在不同的 iOS 设备上接收后)

void *buffer = malloc(255);
[data getBytes:buffer length:sizeof(unsigned int)];
unsigned int _state = (unsigned int)buffer;
....

我正在使用缓冲区,因为最终会有许多不同的整数/浮点数等存储在 NSData 中。第一个 int 可以确定消息的类型,第二个 int - 存储的浮点数等...我使用苹果游戏中心 api 发送和接收数据:

- (BOOL)sendData:(NSData *)data toPlayers:(NSArray *)playerIDs withDataMode:(GKMatchSendDataMode)mode error:(NSError **)error
-(void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID

但问题是,当我解压单个 int 时,我得到的不是 66,而是一些随机值,例如 401488960 或 399903824(每次解压时都不同,即使我每次都发送 66)。 为什么数据不正确?我是不是解包不正确?

【问题讨论】:

    标签: ios objective-c nsdata game-center gamekit


    【解决方案1】:

    您将指针buffer 转换为unsigned int:您将内存地址分配给_state,而不是该地址处的值。改为使用适当类型的指针 (unsigned int *),并取消引用它:

    unsigned int _state = *(unsigned int *)buffer;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-04
      • 2019-11-29
      • 2013-03-08
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      相关资源
      最近更新 更多