Separate a .txt file into separate strings - objective-c

I already know how to upload a file and place its contents into a string with:
NSString *fileContents = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"WellBalanced Recipes" ofType:#"txt"]
encoding:NSUTF8StringEncoding
error:NULL];
However, I would like to parse this text document into separate strings. For example, if I had different recipes in the same document, I would like to somehow separate each recipe.

Use - (NSArray *)componentsSeparatedByString:(NSString *)separator
NSArray *data = [fileContents componentsSeparatedByString:#"\n"];

Related

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

Writting the contents of an array to a text file

I'm trying to take the contents of an array and save that data into a text file and then email that file. The text file shows up on the email screen, but when I actually receive the email, nothing is attached. I'm not getting any errors, but I'm also not sure that my data is actually being written into my text file.
// create text file
NSString *path = [[NSBundle mainBundle] pathForResource:#"EmailSignUpData"
ofType:#"txt"];
NSError *error = nil;
NSString *data = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
// write the contents of the array into the text file to send
[personArray writeToFile:data atomically:YES];
// attach the text file
NSData *myData = [NSData dataWithContentsOfFile: path];
[mailer addAttachmentData:myData mimeType:#"text/plain"
fileName:#"EmailSignUpData.txt"];
Thanks for the help in advance!!

Download and parse textfile in Objective-C

So far I've kept app data on remote servers in the plist format. Downloading and parsing this format is relatively easy:
NSURL *url = [NSURL URLWithString:#"http://www.mysite.com/data.plist"];
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfURL:url];
How can I download a text file with an arbitrary format using Objective-C?
An example of arbitrary format is a file that's two sections of CSV data separated by a few blank lines. Of course I'll know the format ahead of time.
Use -[NSString initWithContentsOfURL:encoding:error:, like so
NSURL *url = [NSURL URLWithString:#"http://www.mysite.com/data.plist"];
NSError *error = nil;
NSString *text = [[NSString alloc] initWithContentsOfURL: url
encoding: NSUTF8StringEncoding
error: &error];
This will get you the file's contents which you can treat however you need to.

Save NSDictionary to plist

I am using the code found in this post: Mulitple Arrays From Plist, with the same plist formatting.
This works successfully, however I do not know how to save the created arrays back into a plist, in the same format.
How would I achieve this?
EDIT: It is not so much the saving that I need, but the forming of the data to save.
The plist is an array of dictionaries with strings and their corresponding keys.
All the strings with a certain key are put into an array of their own.
How would I put that array back into the correct positions in the array of dictionaries, ready to save?
Here's the simplest way:
NSDictionary* dict = ...;
[dict writeToFile:#"..." atomically:YES];
See the documentation for -writeToFile:atomically:.
Don't forget to create myPlistFile.plist and add it in your application resource folder.
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
you could scan paths here and search myPlistFile.plist using for loop.
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"myPlistFile.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath: plistPath])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"myPlistFile" ofType:#"plist"];
[[NSFileManager defaultManager] copyItemAtPath:bundle toPath:plistPath error:&error];
}
[myDict writeToFile:plistPath atomically: YES];
And conversely, to load a NSDictionary FROM a file:
+ (id)dictionaryWithContentsOfFile:(NSString *)path;

Crash on writeToFile

I'm using quite a simple method of storing file names in a text file. For some reason when I initiate the writeToFile I get a crash:
pathString = [NSString stringWithFormat:#"New FileName - %#.png", identifier];
NSString *currentContents = [NSString stringWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];
NSString *newContents = [NSString stringWithFormat:#"%#:::%#",currentContents, pathString];
NSData *newData = [newContents dataUsingEncoding:NSUTF8StringEncoding];
[newData writeToFile:saveFilePath options:NSDataWritingAtomic error:nil];
It reads the file, places it's contents into a variable called currentContents, then adds the new string to the file, and re-writes it. What's going wrong here.
Without the writeToFile line it works, with it, I get a crash.
Origin of saveFilePath
NSString *saveDocument = [NSString stringWithFormat:#"SavedFile.txt"];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
saveFilePath = [docsDirectory stringByAppendingPathComponent:saveDocument];
An NSLog of saveFilePath reveals a correct path
I think your problem might actually be a missing null character ('\0') at the end of your NSData object. So you finally end up with messed up data. You might want to use -writeToFile:atomically:encoding:error: on your new string right away anyway.
It turns out that the reason the file wasn't writing was because of an unallocated variable:
NSString *currentContents = [NSString stringWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];
should have been:
NSString *currentContents = [[NSString alloc] initWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];