How to pack struct in NSData? [duplicate]

2019-03-20 06:58发布

问题:

Possible Duplicate:
Send and receive NSData via GameKit

I have struct which consists of int variable and 2 float pointers (arrays). How can I pack this struct ib NSData and later unpack it?

回答1:

You can pack the structure using dataWithBytes method 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)];