NSData和结构体struct之间如何转换
用处是当用NSNotification传递数据时需要这个转换,然后把NSData放到userInfo中。 // make a NSData object NSData *myData = [NSData dataWithBytes:&myPacketJoin length:sizeof(myPacketJoin)]; // make a new PacketJoin PacketJoin newJoin; [myData getBytes:&newJoin length:sizeof(newJoin)];
struct msg { uint32_t msgtype; uint32_t param1; uint32_t param2; }; struct msg a; a.msgtype = 123456; a.param1 = 12345; a.param2 = 12345; struct msg ba; NSData *msgData = [[NSData alloc]initWithBytes:&a length:sizeof(a)]; [msgData getBytes:&ba length:sizeof(ba)]; NSLog(@"a:%u", ba.msgtype); NSLog(@"ba:%u", a.msgtype );