Convert NSData To NSString

Tue, Mar 12

In the previous post I wrote a few lines of code to convert an NSString object to an NSData object. In this post I’ll do the opposite, putting the conversion into the context how to print an NSData object to the debugging console.

By default, when you print an NSData object to the console using NSLog, the output will be in hex, it will look something like the following:

<7b0a2020 22417272 61792220 3a205b0a 20202020 ...>

Depending on what the data consists of, it can be quite useful to see the data as text. As an example, I recently needed to verify that I had properly serialized a dictionary into JSON, viewing the output as text provided the information I was after.

In order to view the NSData object as text you need to convert the object to an NSString, here is a one liner to do that:

// Convert NSData to NSString...
NSString *output = [[[NSString alloc] initWithData:data encoding:encoding] autorelease];

Depending on your needs (that is, how long you need to keep the string around) and memory management of choice (e.g. ARC), you may need to tweak the code a bit.

For completeness, here is a method that I keep around to print NSData to the debug console:

- (void)debugNSData:(NSData *)data encoding:(NSStringEncoding)encoding
{
  // Convert NSData to NSString
  NSString *output = [[[NSString alloc] initWithData:data encoding:encoding] autorelease];
 
  NSLog(@"nsdata: %@", output);
}

You can call the method as follows:

NSData *json;
...
[self debugNSData:json encoding:NSUTF8StringEncoding];