Posts Tagged ‘NSString’

Converting NSData to NSString and vice versa

Wednesday, June 23rd, 2010

Since I always forget how to convert a NSData object to NSString and vice versa, I thought I’d write it down as a reference. Every time I work with a REST service and need to know what response I’m receiving, before handing the NSData object to a NSXMLParser, I’m always dumbfounded that I’ve forgotten how to do the conversion.

// From NSString to NSData
NSString *text = @"Some string";
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
 
// From NSData to NSString
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Who knows if it helps some one else.