NSData to NSString conversion - objective-c

I found this method to convert an NSData to an NSString object.
NSData *data = //some data
NSString *string = [NSString stringWithFormat:#"%#", data];
How will the data be decoded? Is NSUTF8StringEncoding applied?
Thank you!

This is not the recommended approach. Instead use:
NSString *newString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This will ensure you have a specified encoding for the data.

In this case, the stringWithFormat: method will send NSData object the description message, get the result, and use that for the content of the newly created string. Essentially, the result is identical to
NSString *string = [data description];
According to NSData's documentation, description returns
An NSString object that contains a hexadecimal representation of the receiver’s contents in NSData property list format.

You probably should be using NSString *string = [[NSString alloc] initWithData: data encoding:SomeFormOfEncoding];
You can view the method details here.
The forms of encoding can be seen here.

Related

How to convert an NSString of JSON objects to an NSArray?

I'm having trouble converting my NSString of JSON objects to an NSArray.
The NSArray object seems to be null.
Here is my NSString JSON code:
NSString* retrievedStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This gives me a printout of:
{"image_link":"schedule_tien_nguyen.jpg","start_time":"18:00","end_time":"19:00","viet_performer":"","english_performer":"Tien
Nguyen","viet_event":"","english_event":"Singing","day":0,"stage":0}
....
I tried to convert the NSString to an NSArray using:
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:
[retrievedStr dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
However the printout of the jsonObject is (null)
I have tried the solutions from here:
Converting an NSString of JSON Data to NSArray and How to convert a JSON String into an NSArray? but it's still printing out null.
The error printout states:
"Garbage at end."
I'm not sure what that means?
Try the following to read your JSON response. As others have mentioned, it's a JSON dictionary, not an NSArray. The dictionary may contain arrays, but the object response itself is a dictionary.
NSString* retrievedStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *imageLink = (NSString *)[retrievedStr objectForKey:#"image_link"]
NSLog(#"%#", imageLink);
use NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

parsing NSString data-getting null value

I am parsing and NSString value but getting null in console. Please help me with the issue.
NSString *responseData = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
NSLog(#"Data: %#", responseData);
NSData *data = [responseData dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *res = [json objectForKey:#"demo"];
NSLog(#"res is %#",res);
I was having a similar problem in one of my projects. I was trying to create NSString from NSData(response from webservice) and i was getting a nil. I found out that using NSASCIIStringEncoding when creating the String solved my problem. It turns out that even though UTF8 has all ASCII chars, char * may not line up correctly for certain characters and by default the init methods do nonlossy encoding which means that nil gets returned when an unexpected char is encountered.
For your case this could be your code.
NSString *responseData = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
NSLog(#"Data: %#", responseData);
NSData *data = [responseData dataUsingEncoding:NSASCIIStringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *res = [json objectForKey:#"demo"];
NSLog(#"res is %#",res);
NOTE: I am not sure why you are doing all the _responseData->data conversion. If you are doing that just to deserialize your _responseData to json object, you could use it directly in NSJSONSerialization. As below.
id json = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:nil];
For more information check out this link.
Maybe error appear because you using different encoding? Try using NSUTF8StringEncoding in NSString and in NSData.
From NSString class reference:
-initWithData:encoding:
Return Value
An NSString object initialized by converting the bytes in data into Unicode characters using encoding. The returned
object may be different from the original receiver. Returns nil if the
initialization fails for some reason (for example if data does not
represent valid data for encoding).
Where are you getting _responseData from? Is it definitely an NSDataobject?
Are you sure that you are using the correct encoding?
Could you print out _responseData and update your question so we can take a look?

NSString plain encoded with NSASCIIStringEncoding to NSData

I packed an object (NSObject) to (NSData) and then encoded it with (NSASCIIStringEncoding) for sending it to a SQLite database with this code:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:canvasView.trazoYorch];
//convert NSData object to plain text for sending it to DB
NSData *data2 = [[NSString stringWithFormat:#"%#",data] dataUsingEncoding:NSASCIIStringEncoding];
NSString *dataStr = [[NSString alloc] initWithData:data2 encoding:NSASCIIStringEncoding];
everything works ok, but when I want to do the Inverse process NSString to NSData I got different results, this is my code for inverse process
NSString *FirmaString = [self traerFirmadeBD]; //returns the string content of DB
NSData *data2 = [FirmaString dataUsingEncoding:NSASCIIStringEncoding];
FirmaYorch *firmaCompleta = [NSKeyedUnarchiver unarchiveObjectWithData:data2];
Any help solving this I will appreciate

merge many bytes arrays into one byte array in objective c

i have Used NSMutableData to merge byte arrays
NSMutableData *payload;
payload = [[NSMutableData alloc] init];
[payload appendBytes:CFBridgingRetain((cm.msgBytes)) length:[cm.msgBytes length]];
NSString *cmdata = [[NSString alloc] initWithData:[payload mutableBytes] encoding:NSUTF8StringEncoding];
i want to keep on adding to payload until done
cmdata is always nil
as initWithData takes NSData so i converted the bytes to NSData but the result is still same
NSData *bytesData = [NSData dataWithBytes:[payload mutableBytes] length:[payload length]];
NSString *cmdata = [[NSString alloc] initWithData:bytesData encoding:NSUTF8StringEncoding];
I think you're confusing things in several places. Where an API says "bytes", it's talking about a C array of bytes; where it says "data", it's talking about an NSData object.
Assuming cm.msgBytes is an NSData object, which it appears to be given that you retrieve its .length, a better version of this code would be:
NSMutableData *payload;
payload = [[NSMutableData alloc] init];
[payload appendData:cm.msgBytes];
NSString *cmdata = [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding];
If you wrote the class cm belongs to, you should probably rename msgBytes to msgData (or even messageData), to match the APIs better.
initWithData takes an NSData not bytes itself
NSString *cmdata = [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding];

Extracting NSString from NSKeyedArchiver

I am trying to extract an NSString from the NSKeyedArchiver as follows:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *coder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[coder encodeInt:1 forKey:#"myField"];
[coder finishEncoding];
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", myString);
The problem is that myString is nil (NSLog prints '(null)'). What is wrong with the above code?
Other posts I've read mention that this is usually due to the encoding being wrong (i.e. the NSMutableData is using a different encoding than UTF-8). I've tried all the different types of encoding though, still no luck.
I don't see where you are encoding a string. Normally you would encode an NSString with the NSKeyedArchiver and then unarchive it using an NSKeyedUnarchiver. It doesn't look like you understand how this all works. I recommend reading about archiving using Obj-C.