Converting NSString to NSData - Exception [NSString dataUsingEncoding]

I converted NSString to NSData to parse 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 follows:

 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 a newline: '\ n'.

Am I right?

Can someone please help me solve this problem?

+6
source share
3 answers

Your error says that you are trying to send dataUsingEncoding:allowLossyConversion: to an NSDictionary instance that does not know what to do with this selector. Make sure your str object is actually a string ...

+9
source

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

 NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding]; 

with this:

 NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding]; 
+3
source

I just checked with my sample line. ** If you could give me your line, I could check out my next code sample.

 NSString *msg = [NSString stringWithFormat:@"tell me \"where\"\n" "is\n" "wrong"]; NSData *theData = [msg dataUsingEncoding:NSASCIIStringEncoding]; NSString* theString = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding]; BOOL isValid = [NSJSONSerialization isValidJSONObject:theString]; NSLog(@"Value %d %@",isValid, theString); 

For me, the value comes 0 and says "where"

is an

wrong

0
source

Source: https://habr.com/ru/post/912183/


All Articles