John Lam 1997 — 2026

Serialization

There’s some interesting XML serialization functionality built into Cocoa. You can write some fairly simple code such as:

NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObject:@"John"]; [array addObject:@"Carolyn"]; if( [array writeToFile:@"people.plist" atomically:YES] ) NSLog( "succeeded" );

which results in the following XML being produced:

... <array> <string>John</string> <string>Carolyn</string> </array>

Apparently Mac OS X uses XML configuration files known as plist files to configure functionality. There is a simple tool called the Property List Editor for editing these files.

I don’t yet know how to serialize arbitrary objects (I tried serializing an NSArray of ABPerson objects, and that didn’t work). Unfortunately, writeToFile failed silently without giving me a clue about what was causing it to fail.

The one thing that I am missing in Cocoa so far is a stream-based I/O model. It seems a bit crufty to have to send messages like writeToFile instead of writeToStream.

2 archived reader comments

Eric Hancock (2003-01-02)

I think you want to look at the docs for NSArchiver.

John Lam (2003-01-04)

Thanks Eric. I’m working through Chapter 9 of Davidson’s book right now and have gotten serialization working with arbitrary objects. I found that the key thing was implementing the NSCoding interface in my data object’s class. Or, in Objective C parlance, declaring that my class conforms to the NSCoding protocol. Slowly but surely the new terminology is sinking in …