NSMutable Array to XML file - objective-c

I have an NSMutableArray of custom objects called Clip. Each clip Object has some NSString properties (clipName,tcIn, tcOut, file path and so on..). How do I write an xml File on disk where each clip in the array is a node of the xml file and its properties are elements of the node?
Thanks in advance
Dario

I think this is what should do you:
//Create xml string
NSMutableString *xmlString = [[NSMutableString alloc] init];
//Add all the data to the string
[xmlString appendFormat:#"<clips>"];
for (Clip *c in clipsArray)
{
[xmlString appendFormat:#"\n\t<clip>"];
[xmlString appendFormat:#"\n\t\t<clipName>%#</clipName>", c.clipName];
[xmlString appendFormat:#"\n\t\t<tcIn>%#</tcIn>", c.tcIn];
...
[xmlString appendFormat:#"</clip>"];
}
[xmlString appendFormat:#"</clips>"];
//Create a variable to represent the filepath of the outputted file
//This is taken from some code which saves to an iPhone app's documents directory, it might not be ideal
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:#"output.xml"];
//Actually write the information
NSData *data = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];

Related

How to write all known time zone names in Objective-C to a file

I'm trying to get a file which contains, on separate lines, all the time zone names contained in the knownTimeZoneNames variable of the NSTimeZone class. I'm quite new to Objective-C, though; here is what I've tried so far:
#import <Foundation/Foundation.h>
#import <stdio.h>
int main(void)
{
FILE *fp;
fp = fopen("knownTimeZoneNames.txt", "w+");
for (NSTimeZone* timezone in [NSTimeZone knownTimeZoneNames]) {
fputs(timezone, fp);
}
fclose(fp);
return 0;
}
The problem is that the file I get does not seem to be human-readable. What would be the correct way to do this?
Take your string write to file.
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//use simple alert from my library (see previous post for details)
[ASFunctions alert:content];
[content release];
}

Objective-C: Saving Archived Data to File Crashes

my inquiry is this: I am saving and loading custom objects to file. Loading and creating files with the data works correctly, however, after a file has loaded, saving again crashes. Long story short, saving a file that has been loaded causes a crash upon saving.
The crash sends me to my custom objects m file:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeInteger:*(time) forKey:#"time"];
[encoder encodeInteger:*(location) forKey:#"location"];
}
//====
Loading the data from file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
initWithContentsOfFile:filePath];
globals.mainData = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
//====
Saving to current file
My breakpoint stop me at: NSData *data = ... //and then crashes
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:currentFileName];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:globals.mainData]; //crashes here
BOOL saved = [data writeToFile:filePath options:NSDataWritingAtomic error:nil];
if (saved) {
NSLog(#"Saved %#", currentFileName);
}else{
NSLog(#"Error - code 2 - Failure to save data");
}
Any advice would be awesome and much appreciated!

Write NSMutableArray to plist not working

I am using plists to save/load an NSMutableArray,
the code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *prsPath = [documentsDirectory stringByAppendingPathComponent:#"records.plist"];
prs = [[NSMutableArray alloc] initWithContentsOfFile:prsPath];
when I am using the last sentence of code somewhere else in my code it says: "prsPath" undeclared. (I am loading my code in ViewDidLoad) When I add an Object it doesn't save it, it doesn't even show up. (Loading the last sentence on add)
I'm using this method and it's work 100%
- (void) writeToPlist: (NSString*)fileName withData:(NSMutableArray *)data
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:finalPath atomically: YES];
/* This would change the firmware version in the plist to 1.1.1 by initing the NSDictionary with the plist, then changing the value of the string in the key "ProductVersion" to what you specified */
}
and this method for reading from plist file:
- (NSMutableArray *) readFromPlist: (NSString *)fileName {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:fileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:finalPath];
if (fileExists) {
NSMutableArray *arr = [[NSMutableArray alloc] initWithContentsOfFile:finalPath];
return arr;
} else {
return nil;
}
}
Hope it can help you.
[[NSMutableArray alloc] initWithContentsOfFile:prsPath] will load a plist ant initialize an array with it. Does you plist exist at that path already? You might also want to log the prsPath to see if it's correct.
Usually you would first check to see if a plist exists at the path by calling [[NSFileManager defaultManager] fileExistsAtPath:prsPath]. If it does not, you initialize an empty array.
Later you save it by calling [prs writeToFile:prsPath atomically:YES].
Note that you can't initialize NSMutableArrays from plists. Arrays and dictionaries loaded from plists are always immutable. You would have to first load the plist into an NSArray and then initialize an NSMutableArray from that NSArray.

iPad app - generating text file

Can someone explain and give example code to do the following steps in my iPad app:
do some things in my app, which generates some data (as a string)
write that data to a text file
be able to plug in my iPad to my computer and grab those text files off
How can I do this?
For writing string in a file use this
NSString *str = #"your string";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:#"data.txt"];
NSError *error;
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
Then set Application supports iTunes file sharing key to YES in your plist file.
When you connect your device with iTunes from there you can save your data.txt
Here is the video how to get files from iTunes
Edited as requested.
NSUserDefaults *deflt = [NSUserDefaults standardUserDefaults];
//this number file is saved, I'm not saving the file name as data0.txt.
//The first file to be saved is data1.txt
int num = [deflt integerForKey:#"fileNameNum"];
num++;
NSString *fileName = [NSString stringWithFormat:#"data%d.txt",num];;
NSString *str = #"your string";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error = nil;
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error == nil) {
//Save the number of the file that you have save in doc directory
[deflt setInteger:num forKey:#"fileNameNum"];
}

How can I read user input text from a textfield and write it to a text file in Xcode?

Is there a way to write a string , which is read from text field, to a .txt file?
NSString *input = [textfield text];
NSString *path = #"myText.txt";
[input writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Yes, ultimately that is the way; but there's a number of other steps you do in order to get from start to finish (you need to have textfield connected to an IBOutlet or in some other way accessible; the path where myText.txt is writing to needs to be writable and therefore you'd probably need to have a longer, more precise path than just the filename; you'd probably need to also send in an actual error parameter that could be set so you could look at the errors being returned when the writeToFile call fails the first few times you run this code).
You will need to define a path, basically where to save the file.
This code will find the Documents folder
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
Here is the code I use to read and write files.
-(void)writeFileToDisk:(id)data
{
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
NSString *fileName = #"MyFileName.txt";
NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName];
[data writeToFile:fileAndPath atomically:YES];
}
-(void)readFileFromDisk
{
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
NSString *fileName = #"MyFileName.txt";
NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:fileAndPath];
NSLog(#"%#",array);
[array release];
}