I’m trying to send a message with game center that contains a struct, roughly following Ray Wenderlich’s guide. In general sending and receiving messages has been no problem, but once I throw anything with a pointer in I get a bit confused. The goal is to send a few strings and a BOOL over as one message. Relevant code follows:
//myfile.h
typedef enum {
kMessageTypeRandomNumber = 0,
kMessageTypeInterstitial
} MessageType;
typedef struct {
MessageType messageType;
} Message;
typedef struct {
Message message;
char *playerName;
char *scores;
BOOL correct;
char *stat;
} MessageInterstitial;
//myfile.m
- (void)sendData:(NSData *)data {
NSError *error;
BOOL success = [[GCHelper sharedInstance].match sendDataToAllPlayers:data withDataMode:GKMatchSendDataReliable error:&error];
if (!success) {
NSLog(@"Error sending init packet:\n%@",error);
}
}
-(void)send{
MessageInterstitial message;
message.message.messageType = kMessageTypeInterstitial;
message.playerName="test";
NSData *data = [NSData dataWithBytes:&message length:sizeof(MessageInterstitial)];
[self sendData:data];
MessageInterstitial * myMessage = (MessageInterstitial *) [data bytes];
printf("player: %s\n",myMessage->playerName); // prints 'player: test' as expected
}
- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
Message *message = (Message *) [data bytes];
if(message->messageType == kMessageTypeInterstitial)
{
MessageInterstitial * myMessage = (MessageInterstitial *) [data bytes];
printf("player: %s\n",myMessage->playerName); //prints 'player: ' not expected
}
}
It appears that the data is being saved properly, since I’m able to print it back out right away without issue, but my thinking is that the data is pointing to an address in memory, which would make it so it prints out the correct thing on the sending device, but not the receiving device. That being said, I’ve got no clue how to fix this, or how i should be sending strings within a struct if that is in fact the case.
Indeed this seems like the problem, the addresses are addresses in the sending device, not receiving device. You can use char arrays instead, and just allocate enough space from the beginning. This way they will be part of the struct: