Robin Jamieson
Robin Jamieson

Reputation: 1415

Writing data as XML in an app

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.

Upvotes: 1

Views: 793

Answers (1)

Ramin
Ramin

Reputation: 13433

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.

Upvotes: 2

Related Questions