NSData to NSString Conversion

Below example explains how to convert NSData to NSString with Objective-C.

using -[NSString initWithData] function we can convert NSData to NSString. This function returns nil if the encoding is not correct.

Syntax of initWithData

- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;

 

List of Encoding supported by NSString:

enum {
    NSASCIIStringEncoding = 1,		/* 0..127 only */
    NSNEXTSTEPStringEncoding = 2,
    NSJapaneseEUCStringEncoding = 3,
    NSUTF8StringEncoding = 4,
    NSISOLatin1StringEncoding = 5,
    NSSymbolStringEncoding = 6,
    NSNonLossyASCIIStringEncoding = 7,
    NSShiftJISStringEncoding = 8,          /* kCFStringEncodingDOSJapanese */
    NSISOLatin2StringEncoding = 9,
    NSUnicodeStringEncoding = 10,
    NSWindowsCP1251StringEncoding = 11,    /* Cyrillic; same as AdobeStandardCyrillic */
    NSWindowsCP1252StringEncoding = 12,    /* WinLatin1 */
    NSWindowsCP1253StringEncoding = 13,    /* Greek */
    NSWindowsCP1254StringEncoding = 14,    /* Turkish */
    NSWindowsCP1250StringEncoding = 15,    /* WinLatin2 */
    NSISO2022JPStringEncoding = 21,        /* ISO 2022 Japanese encoding for e-mail */
    NSMacOSRomanStringEncoding = 30,

    NSUTF16StringEncoding = NSUnicodeStringEncoding,      /* An alias for NSUnicodeStringEncoding */

    NSUTF16BigEndianStringEncoding = 0x90000100,          /* NSUTF16StringEncoding encoding with explicit endianness specified */
    NSUTF16LittleEndianStringEncoding = 0x94000100,       /* NSUTF16StringEncoding encoding with explicit endianness specified */

    NSUTF32StringEncoding = 0x8c000100,                   
    NSUTF32BigEndianStringEncoding = 0x98000100,          /* NSUTF32StringEncoding encoding with explicit endianness specified */
    NSUTF32LittleEndianStringEncoding = 0x9c000100        /* NSUTF32StringEncoding encoding with explicit endianness specified */
};

NSASCIIStringEncoding is used to convert ASCII data. NSUTF8StringEncoding is used to convert UTF-8 data.

NSData to NSString Example

NSString * str =@"Hello";
NSData * data =[str dataUsingEncoding:NSUTF8StringEncoding]; //Data

//Convert NSData to NSString
NSString * converted =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Data =%@",converted);

Reference:NSString Documentation


I am a Developer. My motto: "Language is not a barrier" http://hayageek.com
All posts by Ravishanker Kusuma