NSString *到Char [](GameCenter发送结构)

时间:2012-04-23 15:06:10

标签: iphone objective-c ios c game-center

我想向GameCenter中的其他玩家发送struct。 我已经阅读了关于此的其他问题,但是,我无法让它们中的任何一个工作。

我需要将@"1234"变成char[4](ex char [0] ='1',char [1] ='2'等)

我尝试了[NSString UTF8String],但它似乎没有做我想要的。

它分配得很好,但当我用NSString *将其拉回[NSString stringWithUTF8String:]时,它会返回空白。

如果有人可以告诉我往返的转换,我们将不胜感激。

感谢。

修改

我无法让它工作:/这是我的代码(删节版):

Matchmaker.h

enum { NChars = 4 };

typedef struct {
    MessageType messageType;
} Message;

typedef struct {
    Message message;
    char code[NChars];
} MessageGameCode;

@interface Matchmaker : CCLayer <GameCenterMasterDelegate>{

    NSString *_code;
}
@property (nonatomic,retain) NSString *_code;

Matchmaker.m

@synthesize _code;
-(void)viewDidLoad{
    self._code = @"1234";
}

- (void)sendCode {
    NSLog(@"Sending Code....");
    MessageGameCode message;
    message.message.messageType = kMessageTypeGameCode;
    NSString * const source = self._code;

    const char* const sourceAsUTF8 = source.UTF8String;

    for (size_t idx = 0; idx < NChars; ++idx) {
        message.code[idx] = sourceAsUTF8[idx];
    }
    NSData *data = [NSData dataWithBytes:&message length:NChars];    
    [self sendData:data];
}

- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
    Message *message = (Message *) [data bytes];
    if (message->messageType == kMessageTypeGameCode) {        

        MessageGameCode *codeMessage = (MessageGameCode *)[data bytes];
        self._code = [[NSString alloc] initWithBytes:codeMessage->code length:NChars encoding:NSUTF8StringEncoding];
        [self setGameState:kGameStateWaitingForStart];
        NSLog(@"Game Code Recieved");
        NSLog(@"Recieved Code: %@",self._code); //This always shows self._code as blank

    }
}

3 个答案:

答案 0 :(得分:7)

您的尝试将失败,因为您传递给+ [NSString stringWithUTF8String:]的cstring未终止。

试试这个:

NSString * result = [[NSString alloc] initWithBytes:bytes
                                             length:4
                                           encoding:NSUTF8StringEncoding];

修改

更完整的演示:

enum { NChars = 4 };
/* requires error checking */
void transmit() {
    NSString * const source = @"1234";

    char tmp[NChars] = { 0 };
    const char* const sourceAsUTF8 = source.UTF8String;

    for (size_t idx = 0; idx < NChars; ++idx) {
      tmp[idx] = sourceAsUTF8[idx];
    }
    /* .. */
}

/* requires error checking */
void receive(const char bytes[NChars]) {
    NSString * result = [[NSString alloc] initWithBytes:bytes length:NChars encoding:NSUTF8StringEncoding];
    /* ... */
}

答案 1 :(得分:1)

一种方法是

char bytes[4];

NSData* data = [@"1234" dataUsingEncoding: NSUTF8StringEncoding];
if ([data length] <= 4)
{
    memcpy(bytes, [data bytes], [data length]);
}

走另一条路:

NSString* recodedString = [[NSString alloc] initWithBytes: bytes 
                                                   length: savedLengthFromBefore 
                                                 encoding: NSUTF8StringEncoding];

答案 2 :(得分:1)

这里有一些可能的陷阱。

一个是[NSString UTF8String] "The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created."。因此,根据您期望值的持续时间,您可能需要复制它(例如,使用strcpy

另一个问题是[NSString UTF8String][NSString stringWithUTF8String:]都期望以NULL结尾的C字符串,所以你需要一个char [5],而不是char [4]来保存@&#34; 1234& #34 ;.