2012-09-08 28 views
7

Duplicar posibles:
Send and receive NSData via GameKitCómo empacar struct en NSData?

tengo struct que consiste en int variables y 2 punteros flotador (arrays). ¿Cómo puedo empaquetar este struct ib NSData y luego descomprimirlo?

+1

Uso [ 'dataWithBytes'] (http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation /Classes/NSData_Class/Reference/Reference.html#//apple_ref/occ/clm/NSData/dataWithBytes:length :) y suministro '(const void *) & struct_data' y' sizeof struct_data' – oldrinb

Respuesta

10

Puede empaquetar la estructura utilizando dataWithBytes método de 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)]; 
+0

¡Gracias! ¿Puedes mostrar también que hay float * x y float * y en struct cómo inicializarlos, agregar números y luego obtenerlos de la estructura desempaquetada? Porque mi realización no funciona y obtengo otros números en matrices, no es que ponga en – Mathemage

+2

@ValentinKhrulkov si estas estructuras representan datos que necesitan ser serializados y persisten fuera del contexto de la aplicación en ejecución, entonces no creo que funcione bien para que tengas punteros dentro de ellos. –

+0

@Carl Veazey nono, dentro de la aplicación, ¿cómo hacerlo? – Mathemage