如何在NSData中打包struct?

时间:2012-09-08 06:24:32

标签: objective-c nsdata

  

可能重复:
  Send and receive NSData via GameKit

我有一个struct,它由int变量和2个float指针(数组)组成。我如何打包这个结构ib NSData,然后解压缩它?

1 个答案:

答案 0 :(得分:10)

您可以使用dataWithBytes方法打包结构pf NSData:

struct aStruct {
/* Implementation */
};

//Struct variable 
aStruct exampleStruct;

// pack the struct into an NSData Object
NSData *myData = [NSData dataWithBytes:&exampleStruct length:sizeof(exampleStruct)];

// get back the the struct from the object
[myData getBytes:&exampleStruct length:sizeof(exampleStruct)];