Send NSString via Game Center

前端 未结 2 1528
心在旅途
心在旅途 2021-01-29 02:28

I want to send NSString form another one to another one iPhone/iPad via Gamecenter but it crash with EXC_BAD_ACCESS

here in .h file

typedef enum {
    kM         


        
相关标签:
2条回答
  • 2021-01-29 03:00

    try this:

    To encode:

    NSData *data = [stringToEncode dataUsingEncoding:NSUTF8Encoding];
    

    which you can send using Game Center

    To decode:

    NSString *recievedString = [NSString stringWithUTF8String:[recievedData bytes]];
    

    Edit: Now I think you can even put this data in one of your message structs and do the same [NSData dataWithBytes:&message length:sizeof(MessageSubmit)] trick and send it.

    0 讨论(0)
  • 2021-01-29 03:12

    You can't do this:

    NSData *data = [NSData dataWithBytes:&message length:sizeof(MessageSubmit)];    
    

    ...or this:

    MessageSubmit * messageSubmit = (MessageSubmit *) [data bytes];
    

    Generally speaking, you can't just send the in-memory representation of objects around as-is. For example, the submitTile instance variable of that class is a pointer to an NSString object. When you send the data over the network, you aren't sending the string itself, you are sending the pointer - which is just a memory address of a chunk of memory on the sending device. The receiving device won't have the same string stored anywhere, and it wouldn't have the same memory address even if it did. So you've got a nonsensical pointer pointing to nowhere, and you're expecting it to point to a string that doesn't exist.

    The easiest way of doing what you want to do is to make your MessageSubmit class NSCoding-compliant. Serialise it into NSData instead of just making a copy of the bytes.

    0 讨论(0)
提交回复
热议问题