7

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?

Community
  • 1
  • 1
Mathemage
  • 315
  • 4
  • 13
  • 1
    Use [`dataWithBytes`](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html#//apple_ref/occ/clm/NSData/dataWithBytes:length:) and supply `(const void *) &struct_data` and `sizeof struct_data` – obataku Sep 08 '12 at 06:30

1 Answers1

10

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)];
aleroot
  • 71,077
  • 30
  • 176
  • 213
  • Thanks! Can you also show is there are float*x and float*y in struct how to initialize them,add numbers and later get them from unpacked struct? Coz my realisation doesnt work and i get another numbers in arrays,not that I put into – Mathemage Sep 08 '12 at 07:14
  • 2
    @ValentinKhrulkov if these structs represent data that needs to be serialized and persisted outside of the context of the running application then I don't think it will work well for you to have pointers inside of them. – Carl Veazey Sep 08 '12 at 07:26
  • @Carl Veazey nono,inside app,just how to do it? – Mathemage Sep 08 '12 at 08:51
  • Just out of curiosity, is it possible to save this data to disk afterwards? – Andy Ibanez Sep 08 '12 at 22:49