What's a good way to archive the data from a class into XML and write it out to a file? (in Objective-C for iPhone SDK)
I see lots about using NSXMLParser to parse the data but not much on creating the files.
What's a good way to archive the data from a class into XML and write it out to a file? (in Objective-C for iPhone SDK)
I see lots about using NSXMLParser to parse the data but not much on creating the files.
That depends entirely on the language and the nature of your data. There are libraries in any language that will do the actual XML generation for you, requiring only that you specify the data schema you're using. Without knowing specifics, I can't recommend anything specific.
Since you asked for easiest way... if you can get the data into an array or dictionary you can write it out as an XML plist with one line of code:
NSMutableDictionary* data = [NSMutableDictionary
dictionaryWithContentsOfFile:saveDataPath];
[data writeToFile:saveDataPath atomically:YES];
Dictionaries and arrays can contain other dictionaries and arrays as values which helps model nested hierarchies.
Since you can only write to the Documents folder at runtime you'll want something like this to establish the path:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* saveDataPath = [documentsDirectory
stringByAppendingPathComponent:SAVEFILENAME];
For custom marshalling of objects then you'll want to look into NSCoding
and archives. Most of the XML libraries out there don't handle generation so you'll have to roll your own.
Another option is to go the CoreData way and let it take care of the reading and writing for you. But it currently supports SQLite, binary, and in-memory persistent stores, so no XML just yet.