简体   繁体   English

将NSString转换为NSMutableData,而无需转换为NSData

[英]NSString into NSMutableData without conversion to NSData

my problem is the following. 我的问题是以下。 I would like to encapsulate a NSString in a NSMutableData object. 我想将NSString封装在NSMutableData对象中。 But I would like to do it together with other items and without first encapsulating it into a NSData. 但是我想将其与其他项目一起使用,而无需先将其封装到NSData中。 It's only bytes after all isn't it? 毕竟只是字节吗?

My final NSMutableData object would look something like 我最后的NSMutableData对象看起来像

[header | stringLength | NSString]

where header is a char and stringLength is an unsigned short. 其中header是一个字符, stringLength是一个无符号的short。 I build my packet like this 我像这样建立我的包

unsigned short stringLength = myString.length;
NSMutableData* nData = [NSMutableData dataWithBytes:(const void*)&header length:sizeof(char)];
[nData appendBytes:(const void*)&dataLength length:sizeof(unsigned short)];
[nData appendBytes:(const void*)myString length:stringLength];

I would then send this over a gkSession and at the other end I would extract the sting lenght and then the string itself: 然后,我将通过gkSession发送此消息,在另一端,我将提取字符串长度,然后提取字符串本身:

NSString* temp = [NSString alloc];
[data getBytes:(void*)&temp range:NSMakeRange(sizeof(char)+sizeof(unsigned short), stringLenght)];

For some reasons this is giving me bad memory access. 由于某些原因,这给了我不好的内存访问权限。 I suspect that myString.length is not doing exactly what I would expect. 我怀疑myString.length并没有完全符合我的期望。 Do you have any hints? 你有什么提示吗? Thanks in advance. 提前致谢。

This line is incorrect: 这行是不正确的:

[nData appendBytes:(const void*)myString length:stringLength];

This is encoding the first part of the underlying NSString structure (which is larger than stringLength ). 这是对基础NSString结构的第一部分进行编码(大于stringLength )。

What you mean is: 您的意思是:

[nData appendBytes:[myString UTF8String] 
            length:[myString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];

length is the number of characters. length是字符数。 This can be substantially smaller than the number of bytes for multibyte characters. 这可以大大小于多字节字符的字节数。

Just as a side note: if you can shorten your length to 1 byte (0-255), then that encoding is called a Pascal String, and CFString can handle that encoding natively (see CFStringGetPascalString() ). 只需注意一点:如果您可以将长度缩短到1个字节(0-255),则该编码称为Pascal String, CFString可以原生处理该编码(请参阅CFStringGetPascalString() )。 Not something you generally want to do, but interesting. 这不是您通常想要做的,但是很有趣。 It's particularly nice with CFStringCreateWithPascalStringNoCopy() , since you can avoid the memory copy operation entirely. CFStringCreateWithPascalStringNoCopy()尤其CFStringCreateWithPascalStringNoCopy() ,因为您可以完全避免执行内存复制操作。 This is mostly for legacy support, and I wouldn't jump through any hoops to use it, but sometimes it's handy. 这主要是为了获得旧版支持,我不会一any而就地使用它,但是有时它很方便。

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

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