IOS: Different Approaches to Converting NSString to NSData

There are various approaches for converting NSString to NSData.

NSString *req_string = @"I am a NSString."; NSData *req_data = [NSData dataWithBytes:[req_string UTF8String] length:[req_string length]]; // or NSData *req_data_alt = [req_string dataUsingEncoding:NSUTF8StringEncoding]; 

Any difference between the two approaches?

+4
source share
2 answers

The latter ( NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding] ) is an option that I would recommend.

Why?

Some people will say effectiveness. In this case, using the string instance method to create an NSData object, only one obj-c message needs to be sent to Apple code, which is highly optimized. In another case (creating a new NSData object using the class method), you will need two messages for your string object and 1 sending a message to the NSData class object.

However, the runtime is unlikely to change much, and even if it does, the encoding cost will be based on the length of the string, and not on what methods you use to create the NSData object.

I would say that the real reason you want to use the instance method in NSString is semantics and clarity.

Let's look at the pseudo-English translation of these options:

  • [string DataUsingEncoding:NSUTF8StringEncoding] : Hey string, I want you to give me a copy of NSData using UTF8 encoding. Well, thanks, put it right there - no, not on the mat.
  • [NSData dataWithBytes:[req_string UTF8String] length:[req_string length]] : String! Give me all your UTF8 bytes. yeah oh i need your length too Sec. NSData, go here, I need you to take this thing, and go to my doorstep and turn it into data objects, strings, expectations, gently! Don't break anything "

What seems more understandable to you?

+6
source

Your first call is incorrect. [req_string length] not necessarily the length, in bytes, of its -UTF8String . You must use strlen to get the real length of -UTF8String .

This example shows that it is better to use -[NSString dataUsingEncoding:] - there is one more parameter to make a mistake.

Also note: the docs for -[NSString dataUsingEncoding:] indicate that the returned data is an "external representation" intended for transmission to other machines, which may include a specification (byte order marker) on the front panel. In practice, the specification for UTF8 is worse than useless, so -dataUsingEncoding: does not include it. If you chose a different encoding, you could see it.

+4
source

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


All Articles