简体   繁体   English

操纵nsmutabledata

[英]manipulating nsmutabledata

Hi I am trying to create a packet that I want to send over the network to a server, I have pretty much got the packet sorted however its missing a length identifier which I need to calculate at the end of my method and add into the packet. 嗨,我正在尝试创建一个要通过网络发送到服务器的数据包,我已经对数据包进行了排序,但是缺少一个长度标识符,我需要在方法末尾计算并添加到该数据包中。

The packet structure is like this 包的结构是这样的

  • leading value identifier (UInt16) 前导值标识符(UInt16)
  • content size (UInt32) 内容大小(UInt32)
  • packet Content (string) 包内容(字符串)

currently my method looks something like this 目前我的方法看起来像这样

- (NSMutableData *) addRegCode
{
    //Supply some default string for testing
    NSString *regCode = [[NSString alloc] initWithString:@"abcd1"];
    //create NSData object
    NSData *registrationCodeData = [regCode dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableData * RegistrationCodeMutableData = [[NSMutableData alloc] init]; //send this object
    //create leading value
    UInt16 leadingValue = 8;
    NSData * leadingValueData = [[NSData alloc] initWithBytes:&leadingValue length:sizeof(leadingValue)];

    //append data to mutableData
    [RegistrationCodeMutableData appendData:leadingValueData];
    [RegistrationCodeMutableData appendData:registrationCodeData];

    return RegistrationCodeMutableData;
}

what I would like to know is how to calculate the size of registrationCodeData and then add it between where I append leadingValueData & registrationCodeData 我想知道的是如何计算registrationCodeData的大小,然后将其添加到我附加LeadingValueData和registrationCodeData的位置之间

I think I have to be using dataWithBytes:length: but I'm not 100% sure of how to use this 我想我必须使用dataWithBytes:length:但我不确定如何使用此功能

this should do it. 这应该做到。

NSUInteger size = [registrationCodeData length];
NSData *sizeData = [NSData dataWithBytes:&size length:sizeof(size)];
[RegistrationCodeMutableData appendData:leadingValueData];
[RegistrationCodeMutableData appendData:sizeData];
[RegistrationCodeMutableData appendData:registrationCodeData];

also of note using capital letters to start variable names is a little atypical and can be confusing to read! 还需要注意的是,使用大写字母开头的变量名有点不典型,并且可能使阅读混淆!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM