Objective-C Convert NSData to NSString

10,511

Solution 1

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.

Solution 2

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

:)

Share:
10,511
Admin
Author by

Admin

Updated on June 14, 2022

Comments

  • Admin
    Admin almost 2 years

    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?

  • eric
    eric over 6 years
    in your rush to do an "ooh, in swift..." comment, you may want to read the OP's actual question