Extracting NSString from NSKeyedArchiver - objective-c

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.

Related

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?

Is it possible to read and write to a .h file with objective c?

I'm trying to make an xcode plugin that needs to write something to the .h file from the .m file. I haven't been able to find a stackoverflow post with an answer on how to do this. I've tried this code
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSString *contents = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
I've also tried using the StringWithContentsOfFile method, however they both return nil. Is it because you can't read an .h file with this code or is it something else I'm missing.
filePath is this and it's a correct filepath, my ftp client can read it atleast file:///Users/myUserName/Documents/code/macOsDev/XcodePlugIns/XcoderPlugin/XcoderPlugin/XcoderPlugin.h
So my question is, how do I read and write to a .h file? Thanks in advance.
EDIT as requested, some more code however this is as far as I've gotten to the read/write part of my plugin.
NSString *filePath = path;
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSString *contents = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSError *error;
NSString *contents1 = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
contents is #"" because data is nil
and contents1 is just nil;
error is error
NSError * domain: #"NSCocoaErrorDomain" - code: 260
in the debugger, but I'm not sure I'm using this error thing correctly.
Use "/Users/myUserName/Documents/code/macOsDev/XcodePlugIns/XcoderPlugin/XcoderPlugin/XcoderPlugin.h".
Dont use 'file://' prefix
Following is the code for reading and writing
NSString *path = #"your/path/tp/.h/file";
NSData *data = [NSData dataWithContentsOfFile:path];
//Get the contents of the file into the mutable string
NSMutableString *contents = [[NSMutableString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
//Make changes to your mutable string
[contents appendString:#"abc"];
//Write it back to the file
[contents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

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];

NSData to NSString conversion

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.

Convert NSData to a NSURL

I have seen this done the other way. But I have a NSData object returned that is suppose to be a URL of an image file.
How do I do this convert a NSData object into a NSURL?
Thanks
You first need to convert the NSData object to an NSString object and then you can just create a NSURL with the new string.
NSString *urlString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding]; // Or any other appropriate encoding
NSURL *url = [[NSURL alloc] initWithString:[urlString autorelease]];