Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning NSData back to plain text NSString

I have a simple NSString and I'm converting it to NSData :

NSData *data = [[NSData dataWithBytes:[[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding] 
                              length:[[NSString stringWithFormat:@",%@",self.targetId] lengthOfBytesUsingEncoding:NSASCIIStringEncoding]] retain];

Now I want to get the plain text from the NSData object.
If I'm doing that :

NSString* dataStr = [NSString stringWithFormat:@"%@",data];

- I'm getting just an hex expression (i.e <9c3f473e 02000000 0b0000>) and not the plain string I want !

I've tried also using initWithData -

    NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

But it always shows gibrish, no matter which encoding I give it.

Can you please help here ?? :)

like image 407
Guys Avatar asked Jan 22 '11 11:01

Guys


2 Answers

You need to simplify your first code snippet to:

NSData *data = [[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding] 

And then your second decoding snippet will work:

NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
like image 168
grahamparks Avatar answered Nov 15 '22 00:11

grahamparks


Do following change it will work.

NSData *data = [[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding] ;

You did NData of data.

like image 20
Girish Kolari Avatar answered Nov 14 '22 23:11

Girish Kolari