结构到NSData到结构?

时间:2011-03-21 03:30:40

标签: iphone objective-c xcode ios4

我有以下结构:

typedef enum
{
    kPacketTypeJoin = 1,
    kPacketTypeServerAcceptedJoin,
    kPacketTypeSelectedNumber,
} PacketTypes;    
typedef struct
{
    PacketTypes type;
    NSString *name;
} PacketJoin;

我如何将PacketJoin转换为NSData并再次转换回PacketJoin?

1 个答案:

答案 0 :(得分:38)

// make a NSData object
NSData *myData = [NSData dataWithBytes:&myPacketJoin length:sizeof(myPacketJoin)];

// make a new PacketJoin
PacketJoin newJoin;
[myData getBytes:&newJoin length:sizeof(newJoin)];