0

I am creating a game that sends some data between devices in multiplayer game centre.

The data I'm sending includes an NSArray & a message to notify the other player of a change in the score.

I have defined the struct for the score message as such:

typedef NS_ENUM(NSUInteger, MessageType) {
    kMessageTypeUpdateScore
};

typedef struct {
    MessageType messageType;
} Message;

typedef struct {
    Message message;
    int score;
} MessageUpdateScore;

And here's the code for receiving the data:

- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {

    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    // data is an array

    Message *message = (Message *)[data bytes];
    if (message->messageType == kMessageTypeUpdateScore) {
        // data is a message
    }

}

My question is - how do I differentiate between the NSArray & Message such that I can unpack the NSData and do different things with it accordingly?

Sudeep
  • 796
  • 6
  • 16
  • Add a *sentinel* byte in the first element of the `NSData` which defines the content. – Droppy Oct 22 '14 at 14:17
  • How can this be done? Is it similar to appending a byte to some mutable data? – Sudeep Oct 22 '14 at 14:43
  • Similar, yes, but you put it at the front. – Droppy Oct 22 '14 at 14:47
  • I've tried doing that, but I get a EXC_BAD_ACCESS error when I try to read it back. Could you outline the steps or code for inserting & reading the byte? – Sudeep Oct 22 '14 at 15:20
  • Well firstly is there no way to create a single data structure that is capable of holding whatever is in the `NSArray` and the score so there is only ever one type of message being sent? – Droppy Oct 22 '14 at 15:21
  • If you're asking whether the content of the array and the score can be merged into a single data structure, then probably not. One, because the score is being sent more frequently than the array and two, because that would create issues in the game when I try to read the array. – Sudeep Oct 22 '14 at 15:29
  • You want to encode/decode the two items into/from a byte stream. Why not use the NSCoder routines to pack it up and instead of writing a file, send the data as a message, and unpack it at the receiving end? – Owen Hartnett Oct 22 '14 at 20:54

1 Answers1

0

I've got the same problem, you can find my solution here: How to Covert struct with an Array of string to NSData and vice versa Swift

if you have found some better solutions please leave some feedback.

You can find a working example here.

Community
  • 1
  • 1
Max_Power89
  • 1,710
  • 1
  • 21
  • 38