2012-09-08 1 views
7

Eventuali duplicati:
Send and receive NSData via GameKitCome impacchettare struct in NSData?

Ho struct che consiste int puntatori galleggiante variabili e 2 (array). Come posso impacchettare questa struct ib NSData e successivamente decomprimerla?

+1

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

risposta

10

Potete imballare la struttura utilizzando dataWithBytes metodo 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

Grazie! Puoi anche mostrare che ci sono float * x e float * y in struct come inizializzarli, aggiungere numeri e poi prenderli dalla struct decompressa? Coz la mia realizzazione non funziona e ottengo un altro numero in array, non quello che inserisco in – Mathemage

+2

@ValentinKhrulkov se queste strutture rappresentano dati che devono essere serializzati e mantenuti al di fuori del contesto dell'applicazione in esecuzione quindi non penso che funzionerà bene per voi di avere dei puntatori all'interno di loro. –

+0

@Carl Veazey nono, all'interno dell'app, come si fa? – Mathemage