Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting NSString to NSData - [NSString dataUsingEncoding] exception

I was converting NSString to NSData in order to parse by JSON, but I got the following error.

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
  reason: '-  [__NSCFDictionary dataUsingEncoding:]: 
  unrecognized   selector sent to instance 0x7987d60'

The code is as followings:

NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding]; 
//NSUTF8StringEncoding also failed.
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

In my opinion, this is because str contains new-line character:'\n'.

Am I correct?

Would somebody please help me to solve this problem?

like image 311
Fury Avatar asked Apr 01 '12 18:04

Fury


2 Answers

Your error says that you are trying to send dataUsingEncoding:allowLossyConversion: to an instance of NSDictionary, which doesn't know what to do with that selector. Make sure your str object is actually a string...

like image 108
jmstone617 Avatar answered Sep 16 '22 23:09

jmstone617


Try using NSUnicodeStringEncoding instead of NSASCIIStringEncoding. So replace the line:

NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding]; 

with this:

NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding]; 
like image 36
Fernando Cervantes Avatar answered Sep 18 '22 23:09

Fernando Cervantes