NSData 与 struct 以及XML的转换。
在做OC与C++ 混编的时候,我们可能会用到struct 与NSData的相互转换。在这里做一个记录
1、struct转换为NSData
例如如下的struct:
struct tagPackageHead { tagPackageHead() { memset(this,0,sizeof(*this)); bStartcode = 0xFE; } Byte bStartcode; uint iCmd; uint iXMLLen; uint iSeqNumber; Byte bExpand[10]; };
struct tagPackageHead tagPack; tagPack.bStartcode = 0xFE; tagPack.iCmd = CMD_CLIENT_LOGIN; tagPack.iXMLLen = data.length; tagPack.iSeqNumber = 1;以上是在OC中定义一个结构体,然后需要转换为NSData。转换的过程如下:
NSData *headerData = [NSDatadataWithBytes:&tagPacklength:sizeof(tagPack)];
2、NSData转换为struct
struct tagPackageHead tagPack; [data getBytes:&tagPack length:sizeof(tagPack)]; NSLog(@"tagPack.iXMLLen:%d",tagPack.iXMLLen); NSLog(@"tagPack.iCmd:%d",tagPack.iCmd); NSLog(@"tagPack.iSeqNumber:%d",tagPack.iSeqNumber);
//创建XML GDataXMLElement *rootElement = [GDataXMLNode elementWithName:@"SignInReq"]; GDataXMLElement *element = [GDataXMLNode elementWithName:@"ClientType" stringValue:@"PC"]; [rootElement addChild:element]; element = [GDataXMLNode elementWithName:@"UserName" stringValue:@"abcdef"]; [rootElement addChild:element]; element = [GDataXMLNode elementWithName:@"Password" stringValue:@"123456"]; [rootElement addChild:element]; element = [GDataXMLNode elementWithName:@"UserAgent" stringValue:@"1.01"]; [rootElement addChild:element]; GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithRootElement:rootElement]; NSData *data = [document XMLData];
4、解析XML文件
因为服务器返回的数据中有包头和XML文件两部分,所以要先获取包头,然后再获取XML文件
struct tagPackageHead tagPack; [data getBytes:&tagPack length:sizeof(tagPack)]; NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSString *string = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(sizeof(tagPack), tagPack.iXMLLen)] encoding:enc]; NSData *data2 = [string dataUsingEncoding:NSUTF8StringEncoding]; NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path=[paths objectAtIndex:0]; NSString *areaDevice_path=[path stringByAppendingPathComponent:@"areaDevice.xml"]; //==写入文件 [data2 writeToFile:areaDevice_path atomically:YES]; //开始解析 NSDictionary *dict = [NSDictionary dictionaryWithXMLData:data2];这里第二行的data,就是从服务器返回的NSData类型的data,先获取包头,因为服务器返回的格式是GBK格式,所以转码一次,然后保存到本地后,解析转换为字典,解析用的第三方是XMLDictionary。