How to use NSString getBytes: maxLength: usedLength: encoding: options: range: left

I have a string that I want as an array of bytes. So far I have used NSData for 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 a getBytes:maxLength:usedLength:encoding:options:range:remainingRange: , which will let me skip everything together using NSData. My problem is that I do not know how to set all the parameters correctly.

I assume that the accepted array of pointers should be malloc'ed, but I'm not sure how to find how much memory there is for malloc. I know that there are [NSString lengthOfBytesUsingEncoding:] and [NSString maximumLengthOfBytesUsingEncoding:] , but I don’t know if those methods are needed and I don’t quite understand the difference between them. I assume this will be the same value as for maxLength . Other parameters make sense from the documentation. Any help would be great. Thanks.

+4
source share
1 answer

The difference between lengthOfBytesUsingEncoding: and maximumLengthOfBytesUsingEncoding: is that the former is accurate but slow (O (n)), while the latter is fast (O (1)), but can return a significantly larger number of bytes than on the actual business is necessary. The only guarantee that maximumLengthOfBytesUsingEncoding: gives is that the return value will be large enough to contain string bytes.

As a rule, your assumptions are correct. Therefore, the method should be used as follows:

 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); 
+5
source

Source: https://habr.com/ru/post/1379763/


All Articles