converting NSString to NSData - [NSString dataUsingEncoding] exception

20,819

Solution 1

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

Solution 2

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

NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding]; 

with this:

NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding]; 
Share:
20,819
Jun
Author by

Jun

Updated on June 26, 2020

Comments

  • Jun
    Jun almost 4 years

    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?

  • Jun
    Jun about 12 years
    You're right. It was my mistake. str object is actually NSDictionary as this error says:[__NSCFDictionary dataUsingEncoding:]
  • Parth Bhatt
    Parth Bhatt about 12 years
    This is not a proper answer. You need to add more detail to your answer.
  • Taimur Ajmal
    Taimur Ajmal over 7 years
    @Harry How did you solve it. Can you please mention. Thanks a lot.
  • Pankaj Bhardwaj
    Pankaj Bhardwaj over 7 years
    @TaimurAjmal You just ned to change your dictionary object in string like this - NSString* json = [NSString stringWithFormat:@"%@", responseObject]; and then use this their will be no exception