Turning NSData back to plain text NSString

2019-06-21 21:42发布

问题:

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 ?? :)

回答1:

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];


回答2:

Do following change it will work.

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

You did NData of data.