Search code examples
iphonejsonios5nsdata

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?


Solution

  • 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...