Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS : Different Approaches of converting NSString to NSData

There are different approaches of 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 these 2 approaches?

like image 329
Raptor Avatar asked Dec 06 '25 02:12

Raptor


2 Answers

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

Why?

Some people will say efficiency. In this case, using the string instance method to create a NSData object requires only a single obj-c message dispatch to Apple's code, which is highly optimized. In the other case (creating a new NSData object using the class method) would require 2 message dispatches to your string object and 1 message dispatch to the NSData class object.

However, the runtimes are unlikely to vastly differ, and even if they do, the cost of the encoding is going to be based on the length of the string, and not what methods you use to create the NSData object.

I would argue the real reason you would want to use the instance method on NSString is semantics and clarity.

Let's consider an pseudo-english translation of these options:

  • [string DataUsingEncoding:NSUTF8StringEncoding]: Hey, string, I want you to give me a NSData copy of yourself using UTF8 encoding. Ok, thanks, put that right over there - no, not on the rug.
  • [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, get over here, I need you to pick up this stuff string is leaving on my doorstep and turn it into a data objec- hey, string, wait, gently! Don't break anything"

Which seems clearer to you?

like image 94
locriani Avatar answered Dec 07 '25 18:12

locriani


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

This example shows that using -[NSString dataUsingEncoding:] is better -- there is one fewer parameter to get wrong.

Also note: the docs for -[NSString dataUsingEncoding:] state that the returned data is an "external representation", meant to be transmitted to other machines, that may include a BOM (byte order marker) on the front. In practice, the BOM is worse than useless for UTF8, so -dataUsingEncoding: doesn't include it. If you were to pick a different encoding, through, you might see it.

like image 20
Kurt Revis Avatar answered Dec 07 '25 18:12

Kurt Revis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!