IOS IM Development preparations (5) How to Handle struct in iOS, iosstruct
There are not many opportunities for iOS to process struct: Blueteeth or socket and so on...
However, one day you will still meet.
Fixed Length struct
The so-called fixed length struct specifies the length of bytes for each field in the structure. Such as int, long, double, char [32. The following is an example of a fixed-length struct.
typedef struct tagInfo{ int nFace; long cmd; char sNickName[60]; char sAccountNo[60];}T_INFO,*PT_INFO;
In my opinion, the struct is an ordered binary text. That is, each of its fields is arranged in order.
// Assign tagInfo * tinfo; tinfo-> nFace = 0; memcpy (tinfo-> sAccountNo, [@ "xxx" UTF8String], 60); memcpy (tinfo-> sNickName, [@ "xxx" UTF8String], 60); tinfo-> cmd = 10;
// Process the data in binary format to send NSData * sendData = [[NSData alloc] initWithBytes: tinfo length: sizeof (tinfo)];
The above two sections of Code show that each field of the Fixed Length struct can be directly assigned a value using the corresponding method, and the length converted to binary is also fixed. So how can we set this value if it is an accepted struct?
// Process received data NSData * receiveData; // The data you received char * k = new char [receiveData. length]; if (k) {// whether it is null tagInfo * tinfo = new (k) tagInfo (); [receiveData getBytes: tinfo length: receiveData. length]; // the string is the NSString * name to be converted = [[NSString alloc] initWithBytes: tinfo-> sNickName length: 64 encoding: NSUTF8StringEncoding]; NSString * accountNo = [[NSString alloc] initWithBytes: tinfo-> sAccountNo length: 64 encoding: NSUTF8StringEncoding]; int face = tinfo-> nFace; long cmd = tinfo-> cmd ;}
Variable Length struct
This is usually used. Because the length of each sent message is different, it is too long to waste traffic and too little short message content.
Typedef struct tagInfo {int nFace; long cmd; int length; char sNickName [60]; char sAccountNo [60]; char exInfo [1]; // This is an indefinite content} T_INFO, * PT_INFO;
Processing with an indefinite length is related to the size of the struct.
// Assign a value of data to an indefinite NSData type char * l = new char [data. length + sizeof (tagInfo)]; if (l) {memset (l, 0, data. length + sizeof (tagInfo); tagInfo * ksm = new (l) tagInfo (); // It is critical to calculate the length of the struct ksm-> length = (uint32_t) (data. length) + (sizeof (tagInfo); // fill in the fixed length field. The previous fields ksm-> nFace = 0; ksm-> cmd = 11 ;...... // copy data of an indefinite length to the corresponding memcpy (ksm-> bData, data. bytes, data. length); // convert to the binary NSData * returnData = [[NSData alloc] initWithBytes: ksm length: ksm. length];}
Otherwise, the processing is the same as the fixed length. However, the length of the field with an indefinite length must be calculated by length.