data loss when sending across type NSData
I am currently in the middle of implementing the network layer of my game, i am making progress however i have come across something very odd which i was hoping someone could shed some might on:
Before sending my data across i am encoding it into type NSData (message.cards = [MovePlayer beginEncodeMyCards:myCards];) and then assigning it to a pointer (message.cards)
MessageMove message; message.message.messageType = kMessageTypeMove; /**/message.cards = [MovePlayer beginEncodeMyCards:myCards];/**/ NSData *data = [NSData dataWithBytes:&message length:sizeof(message)];
If i do all the decoding on the client side as follows :
MessageMove *myMessage = (MessageMove *) [data bytes]; /**/myCards = [MovePlayer beginDecodeMyCards:myMessage->cards cardArray:myCards];/**/
everything works fine, i am able to decode myMessage->cards, however when i try doing the same after sending the object remotely i can see the correct message type (kMessageTypeMove) but not the cards data (myMessage->cards).
if anyone can please shed some light to this i would greatly appreciate it
tl;dr, use NSCoding to serialise your objects.
You can't send pointers to a different process, because the pointers will all be wrong on the other side.
Lets say on the sending machine, you have this:
NSLog(@"cards: %p", message.cards); //prints "cards: 0xDEADBEEF"
This says that the chunk of memory for the NSArray* object starts at the memory address 0xDEADBEEF. This is all correct at this point.
Now, you send that 0xDEADBEEF pointer to another computer. The computer gets the pointer, but the memory at 0xDEADBEEF does not have an NSArray in it on the other computer. There could be anything in that region of memory. You've sent a pointer, but you haven't actually sent any of the data with it.
Long story short, just use NSCoder for serialisation because it's very good.