Send NSString via Game Center

≡放荡痞女 提交于 2019-12-02 10:03:01

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!