5

Here are the code I tried to convert NSData to NSString but the program return "Program received signal:SIGABRT".

NSString *string= [NSString stringWithUTF8String:[data bytes]];

OR

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

Is there any other better way to do it?

user1746447
  • 61
  • 1
  • 1
  • 2
  • 4
    And if it's not nil, does it actually contain the bytes of a string in UTF-8 encoding? How was the NSData object created? – rmaddy Oct 16 '12 at 02:16
  • 1
    @rmaddy While that would result in an undefined string result (almost certainly just a nil return), it wouldn't result in a SIGABRT on that line. – Jason Coco Oct 16 '12 at 02:32
  • The data is not nil. There is data in NSData variable. – user1746447 Oct 16 '12 at 08:50

3 Answers3

7

Here's a highly up-voted answer that shows how to do it. In a nutshell:

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

The first idea looks like a fail because of sending [data bytes]. stringWithUTF8String isn't prepared for a void *. The second idea looks as if it should work, even with nil input.

Community
  • 1
  • 1
danh
  • 62,181
  • 10
  • 95
  • 136
3

Use this code

NSString* myString;
myString = [[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

also see this tutorial..

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

:)

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
0

Swift-3

enter image description here

let string = data.base64EncodedString()

Shrawan
  • 7,128
  • 4
  • 29
  • 40
  • in your rush to do an "ooh, in swift..." comment, you may want to read the OP's actual question – eric Sep 28 '17 at 22:03