I need to send data across the network as NSData. As the format may be determined only at runtime, (e.g.: Message Type, number of objects etc, types of objects), I am using the following code to pack / unpack the NSData

To pack:

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

To unpack (after receiving on a different iOS device)

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

I am using the buffer, because eventually there will be many different ints/ floats etc stored in the NSData. The first int may determine the type of message, second int - the number of floats stored, etc... I send and receive the data using apples game center apis:

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

But the problem is, when I unpack the single int, instead of getting 66, I get some random value like 401488960 or 399903824 (its different each time I unpack, even though I am sending 66 each time). Why is the data incorrect? Am I unpacking incorrectly?

有帮助吗?

解决方案

You are casting the pointer buffer to unsigned int: you are assigning the memory address to _state, not the value at that address. Use a pointer of the appropriate type (unsigned int *) instead, and dereference it:

unsigned int _state = *(unsigned int *)buffer;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top