32

Possible Duplicate:
Convert UTF-8 encoded NSData to NSString

I need to to convert the NSData read from file to NSString. How to do it?

Community
  • 1
  • 1
tna0y
  • 1,722
  • 3
  • 15
  • 32
  • In swift-3 http://stackoverflow.com/questions/12906598/objective-c-convert-nsdata-to-nsstring/40910967#40910967 – Shrawan Dec 01 '16 at 12:43

3 Answers3

50

NSString provides an initializer for this purpose.

// NSData *data = [NSData data];
NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
modocache
  • 6,168
  • 4
  • 34
  • 49
10

You can do it this way

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

or the ohther way to use it when the data ends with a null is:-

NSString *yourStr= [NSString stringWithUTF8String:[theData bytes]];
Abhishek Singh
  • 6,068
  • 1
  • 21
  • 25
6
NSString *convertedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]
Tomas Camin
  • 9,908
  • 2
  • 40
  • 61