Erik
Erik

Reputation: 2148

NSData to NSString conversion

I found this method to convert an NSData to an NSString object.

NSData *data = //some data
NSString *string = [NSString stringWithFormat:@"%@", data];

How will the data be decoded? Is NSUTF8StringEncoding applied?

Thank you!

Upvotes: 1

Views: 674

Answers (3)

Johnny Gamez
Johnny Gamez

Reputation: 259

You probably should be using NSString *string = [[NSString alloc] initWithData: data encoding:SomeFormOfEncoding];

You can view the method details here.

The forms of encoding can be seen here.

Upvotes: 0

dtuckernet
dtuckernet

Reputation: 7895

This is not the recommended approach. Instead use:

NSString *newString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

This will ensure you have a specified encoding for the data.

Upvotes: 7

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

In this case, the stringWithFormat: method will send NSData object the description message, get the result, and use that for the content of the newly created string. Essentially, the result is identical to

NSString *string = [data description];

According to NSData's documentation, description returns

An NSString object that contains a hexadecimal representation of the receiver’s contents in NSData property list format.

Upvotes: 4

Related Questions