开发者

Array of Char or Storing a string in a struct without a pointer (Not using NSString - I think) in objective C

I'm creating a game in objective C using the cocos 2d engine for iPhone. Currently i'm sending packets of data to and from clients using structs:

typedef struct
{
PacketType type;
CGPoint position;
int amount;
int playerId;
} PacketPlayerDamage;

My problem is I want to send a string in the same format, otherwise I have to make some pretty major changes, ideally the following would work:

typedef struct
{
    PacketType type;
    NSString *name;
} PacketHello

I believe this doesn't work as when i'm wrapping up my packet to send it I do the following:

PacketPlayerDamage packet;
packet.type = kPacketTypePlayerDamage;
packet.amount = amount;
packet.playerId = playerId;
NSData* sendPacket = [NSData dataWithBytes:data length:sizeof(packet)];
[self sendToAll:sendPacket];

Which fails to unwrap a NSString and throws an error, possibly because it doesn't know the size/length of that variable in the struct.

So since, I don't really want to modify the way I wrap or unwrap my data packet (i was converting NSMutableDictionary's to JSON and everything was fine, but that seems like a step 开发者_Go百科backwards) but I want to allow the sending of a string (obviously fixed string length/size is fine, i.e. 32 characters), my question is....

Is there an easy way to handle a fixed length string without a pointer in objective C, array of 32 chars or something similar?

I've seen the following:

UTF8String option1;
Str32 option2;

Are they what i'm looking for? If so, how do I take a max 32 char NSString and apply it to them (, and I guess the title isn't as relevant...)

Thanks for you help,

JT


You can use the - (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding method on NSString. So you would add add a char array to your struct with a fixed length and use the method above to write the NSString into it:

typedef struct
{
    PacketType type;
    char name[MAX_LENGTH];
} PacketHello

NSString* toSend = @"blahblahblah";
PacketHello myPacket;
[toSend getCString:myPacket.name maxLength:MAX_LENGTH encoding:NSUTF8StringEncoding];

On the recieving end you can convert it back to an NSString with - (id)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding

PacketHello received;
NSString* name = [[NSString alloc] initWithCString:received.name encoding:NSUTF8StringEncoding];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜