在两台设备之间发送数据时,数据会混乱

时间:2015-03-06 15:13:50

标签: ios objective-c game-center gamekit

我制作了一款多人游戏,完全可以在iPhone 5s上对抗模拟器。但是每当我尝试用我的5s对抗iPhone 5时,就会出现一些问题。

游戏向另一位玩家发送两个值:得分和等级。

如果iPhone 5s发送值:iPhone 5认为得分= 0且等级=我们作为得分发送的值。

typedef struct {
    NSUInteger score;
    NSUInteger level;
} MessageNewScore;

- (void)sendData:(NSData *)data {
    NSError *error;
    GameKitHelper *gameKitHelper = [GameKitHelper sharedGameKitHelper];

    BOOL success = [gameKitHelper.match sendDataToAllPlayers:data withDataMode:GKMatchSendDataReliable error:&error];
    if (!success) {
        NSLog(@"Error sending data:%@", error.localizedDescription);
    }
}

// Run on iPhone 5s
- (void)sendNewScore:(NSUInteger)score level:(NSUInteger)level{
    NSLog(@"score: %lu", (unsigned long)score); // E.g. 1930
    NSLog(@"level: %lu", (unsigned long)level); // E.g. 7

    MessageNewScore messageNewScore;
    messageNewScore.message.messageType = kMessageTypeNewScore;
    messageNewScore.score = score;
    messageNewScore.level = level;
    NSData *data = [NSData dataWithBytes:&messageNewScore
                              length:sizeof(MessageNewScore)];

    [self sendData:data];

    NSLog(@"score: %lu", (unsigned long)messageNewScore.score); // 1930
    NSLog(@"level: %lu", (unsigned long)messageNewScore.level); // 7
}

// Run on iPhone 5
- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
    MessageNewScore *messageNewScore = (MessageNewScore*)[data bytes];

    NSLog(@"score: %lu", (unsigned long)messageNewScore->score); // According to iPhone 5 this is 0
    NSLog(@"level: %lu", (unsigned long)messageNewScore->level); // According to iPhone 5 this is 1930

    [_delegate enemysScoreReceived:messageNewScore->score level:messageNewScore->level];
}

在最后一种情况下,登录sendNewScore::的值是正确的,而didReceiveData::中的值是错误的。 我认为这可能与5s中的64位处理器有关,但不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:3)

iPhone 5使用Apple A6(32位),iPhone 5S使用Apple A7(64位)处理器。

您需要以便携式表示形式对播放器之间发送的NSData进行编码/解码,例如可以使用NSKeyedArchiver / NSKeyedUnarchiver进行编码/解码NSInteger您正在发送struct,其表示是特定于处理器的。