如何使用 NSString getBytes:maxLength:usedLength:encoding:options:range:remainingRange:
我有一个想要作为字节数组的字符串。到目前为止,我已经使用 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 );
但是,我知道 NSString 有 getBytes:maxLength:usedLength:encoding:options:range:remainingRange: 方法,该方法允许我一起跳过使用 NSData 。我的问题是,我不知道如何正确设置所有参数。
我假设传入的指针数组必须进行 malloc - 但我不确定如何找到要 malloc 的内存量。我知道有 [NSString lengthOfBytesUsingEncoding:]
和 [NSString MaximumLengthOfBytesUsingEncoding:]
但我不知道这些是否是我需要使用的方法并且不完全理解他们之间的区别。我认为这与赋予 maxLength
的值相同。其余参数从文档中是有意义的。任何帮助都会很棒。谢谢。
I have a string that I want as a byte array. So far I have used NSData to do this:
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. 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. 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. I assume this would be the same value given to maxLength
. The rest of the parameters make sense from the documentation. Any help would be great. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
lengthOfBytesUsingEncoding:
和maximumLengthOfBytesUsingEncoding:
之间的区别在于,前者精确但速度慢 (O(n)),而后者速度快 (O(1)) 但可能返回比实际需要的字节数要大得多。maximumLengthOfBytesUsingEncoding:
提供的唯一保证是返回值足够大以包含字符串的字节。一般来说,你的假设是正确的。所以该方法应该这样使用:
The difference between
lengthOfBytesUsingEncoding:
andmaximumLengthOfBytesUsingEncoding:
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. The only guarantee thatmaximumLengthOfBytesUsingEncoding:
gives is that the return value will be large enough to contain the string's bytes.Generally, your assumptions are correct. So the method should be used like this: