Wednesday, July 6, 2011

Tutorial: Archiving and Parsing XML with Objective-C

In Objective-C terms, archiving is the process of saving one or more objects in a format so that they can be later restored. This involves writing the object(s) to a file so it can be subsequently be read back in. 


Archiving with XML Property Lists 


If your objects are of type NSString, NSDictionary, NSArray, NSDate, NSData, or NSNumber, you can use the writeToFile:atomically: method implemented in these classes to write your data to a file. 


In the case of writing out a dictionary or an array, this method writes the data to the file in the format of an XML property list. 


Tutorial


Goal: This tutorial will teach you how to read/write an XML property list with Objective-C.


Saving a Dictionary as an XML Property List


1. Open a Terminal Window and create a new file called archive.m. (i.e. emacs archive.m)


2. Copy and paste the code below. Type CONTROL + X then S to save the file, then type CONTROL + X then C to exit.



3. Compile the code and then run.
(i.e. gcc -framework Foundation archive.m -o arch)
(i.e. ./arch)


4. Type ls then enter and you should see a new file called buildings was created.


5. Open the file and it should match the file below.





Reading a Dictionary from an XML Property List



1. Open a Terminal Window and create a new file called unArchive.m. (i.e. emacs unArchive.m)

2. Copy and paste the code below. Type CONTROL + X then S to save the file, then type CONTROL + X then C to exit.
3. Compile the code and then run.
(i.e. gcc -framework Foundation unArchive.m -o unArch)
(i.e. ./unArch)

4. After you run the program you should have output that matches below.