Converting NSString to NSData and vice versa

Kapil Choubisa picture Kapil Choubisa · Jul 19, 2011 · Viewed 33.4k times · Source

I am having an issue while trying to convert NSString to NSData and vice versa. I am trying to store encrypted string to my database. For that I am using AES algorithm. Now what I am doing is I get encrypted NSData and I am converting this to NSString using following:

// Not woking
NSString *strTemp = [[NSString alloc] initWithData:encData encoding:NSUTF8StringEncoding]; 

// Working
NSString *strTemp = [[NSString alloc] initWithData:encData encoding:NSASCIIStringEncoding];

Why NSData is not converting while using NSUTF8StringEncoding. Same way when I try to convert the string got by NSASCIIStringEncoding using:

// Not working
[strTemp dataUsingEncoding:NSASCIIStringEncoding];

// Working
[strTemp dataUsingEncoding:NSUTF8StringEncoding];

Why NSASCIIStringEncoding is not working while converting the NSString to NSData?

Answer

Maulik picture Maulik · Jul 19, 2011

NSString to NSData:

NSString* str= @"teststring";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

NSData to NSString:

NSString* newStr = [[NSString alloc] initWithData:theData
                                         encoding:NSUTF8StringEncoding];