简体   繁体   English

如何使用NSString getBytes:maxLength:usedLength:encoding:options:range:remainingRange:

[英]How to use NSString getBytes:maxLength:usedLength:encoding:options:range:remainingRange:

I have a string that I want as a byte array. 我有一个想要作为字节数组的字符串。 So far I have used NSData to do this: 到目前为止,我已经使用NSData来做到这一点:

NSString *message = @"testing";
NSData *messageData = [message dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:YES];
NSUInteger dataLength = [messageData length];
Byte *byteData = (Byte*)malloc( dataLength );
memcpy( byteData, [messageData bytes], dataLength );

But, I know that NSString has the getBytes:maxLength:usedLength:encoding:options:range:remainingRange: method that would allow me to skip using NSData all together. 但是,我知道NSString具有getBytes:maxLength:usedLength:encoding:options:range:remainingRange:方法,该方法使我可以一起跳过使用NSData。 My issue is, I don't know how to properly set all the parameters. 我的问题是,我不知道如何正确设置所有参数。

I assume the pointer array passed in has to be malloc'ed - but I'm not sure how to find how much memory to malloc. 我假设传入的指针数组必须是malloc的-但我不确定如何找到要分配的内存量。 I know there is [NSString lengthOfBytesUsingEncoding:] and [NSString maximumLengthOfBytesUsingEncoding:] but I don't know if those are the methods I need to use and don't fully understand the difference between them. 我知道有[NSString lengthOfBytesUsingEncoding:][NSString maximumLengthOfBytesUsingEncoding:]但是我不知道这些是否是我需要使用的方法,并且不完全了解它们之间的区别。 I assume this would be the same value given to maxLength . 我认为这将是与maxLength相同的值。 The rest of the parameters make sense from the documentation. 其余参数在文档中有意义。 Any help would be great. 任何帮助都会很棒。 Thanks. 谢谢。

The difference between lengthOfBytesUsingEncoding: and maximumLengthOfBytesUsingEncoding: is that the former is exact but slow (O(n)) while the latter is fast (O(1)) but may return a considerably larger number of bytes than is actually needed. lengthOfBytesUsingEncoding:maximumLengthOfBytesUsingEncoding:之间的区别在于,前者是精确的但很慢(O(n)),而后者是快速的(O(1)),但返回的字节数可能比实际需要的要大得多。 The only guarantee that maximumLengthOfBytesUsingEncoding: gives is that the return value will be large enough to contain the string's bytes. maximumLengthOfBytesUsingEncoding:给出的唯一保证是,返回值将足够大以包含字符串的字节。

Generally, your assumptions are correct. 通常,您的假设是正确的。 So the method should be used like this: 因此,该方法应像这样使用:

NSUInteger numberOfBytes = [message lengthOfBytesUsingEncoding:NSUnicodeStringEncoding];
void *buffer = malloc(numberOfBytes);
NSUInteger usedLength = 0;
NSRange range = NSMakeRange(0, [message length]);
BOOL result = [message getBytes:buffer maxLength:numberOfBytes usedLength:&usedLength encoding:NSUnicodeStringEncoding options:0 range:range remainingRange:NULL];
...
free(buffer);

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

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