Search code examples
iosmessagensdataexc-bad-accessgamekit

EXC_BAD_ACCESS while sending data with game center


I'm trying to make a multiplayer memory game with game center.

I followed the tutorial in this link, connected two devices to a match, got the match started.

In the game, when one device flip a card, the other must flip that card too.To do this, I have to send an id type value to the other device, so I can flip the card in two devices.

Here is the code;

- (void)gameTouchBegin:(id)target {
    [target flipTheCard];
    [self sendCardMove:target];
}

- (void)sendCardMove:(id)target {   
     MessageCard message;
     message.message.messageType = kMessageTypeCard;
     message.target = target;
     NSData* data = [NSData dataWithBytes:&message length:sizeof(MessageCard)];
     [self sendData:data];
}

- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
    if (message->messageType == kMessageTypeCard) {
    NSLog(@"Other player flipped the card.");
    // I can successfully write this line.
    // So I can reach inside this function.
    MessageCard * messageInit = (MessageCard *) [data bytes];
    id gTarget = (id)messageInit->target;
    [gTarget flipTheCard];

    // At the three code lines above, I got an error.

    }
}

As I commented at the end of the code, I got EXC_BAD_ACCESS error and the app crashes.

I know this is a complicated stuff, anyone have an idea?

Thanks in advance.


Solution

  • I think that may cause the problem.

    I define the message body like this;

    typedef struct {
        Message message;
        id target;
    } MessageCard;
    

    I suppose xCode doesn't let me define "id" type variables in struct. So I can't send id type to other device. There is no solution about that, I must find another way to find out which card it is.

    Thank you.