I am trying to send an Array from one player to another.
I create a struct in the header
typedef struct {
Message message;
unsigned int numBytes;
void * bytes;
} MessagePingBackToCaller;
typedef struct {
MessageType messageType;
} Message;
And try to send with this:
-(void)sendOpponentRadar{
MessagePingBackToCaller sendMessage;
sendMessage.message.messageType = kMessageTypeRecievedRadarPing;
NSData *pingData = [NSKeyedArchiver archivedDataWithRootObject:[cover gatherAndReturnColumnNumbers]];
sendMessage.bytes = pingData;
NSData *data = [NSData dataWithBytes:&sendMessage length:sizeof(MessagePingBackToCaller)];
[self sendData:data];
}
And receive with this:
if (message->messageType == kMessageTypeRecievedRadarPing){
MessagePingBackToCaller *messageSent = (MessagePingBackToCaller *)[data bytes];
NSLog(@"Data : %@", messageSent->bytes);
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:messageSent->bytes];
NSLog(@"Results : %@", array);
}
However no luck, so I went looking around and found that @rwenderlich wrote a little helpful bit:
-
Convert NSArray to NSData
-
In struct, store an unsigned int numBytes, and a void * bytes
-
In numBytes, write the length of the NSData, and then write out the contents of the NSData
-
On the other side, read numBytes to see how many bytes to read next, then read in that amount of bytes and reverse the process (bytes->NSData->NSArray).
Im pretty good on 1 and 2… I believe, but i get lost on 3 and 4. Could someone please help me translate this into meaningful code?
Thanks!
You can just use NSKeyedArchiver to do the trick, dont use the c struct, make it an objective-c class, get data from the thing using NSKeyedArchiver and send that, then just unarchive in the other side, heres an example for an arbitrary class
interface
implementation
now you can get data from the object like
and an object from the data
and your workflow becomes
on the sender side
and on the receiving side
hope it helps