tags:

views:

598

answers:

2

In a game I have a bunch of objects and collections of objects, some of them include references to others. Is there a straightforward way to archive them - to save a game state - while maintaining those references? If I understood well, NSArchiver can do that, but it wasn't available on SDK 2, is it on SDK 3?

(I have sort of asked this question before (http://stackoverflow.com/questions/307681/best-way-to-save-load-iphone-game-data) but SDK 3 has been released in the meantime, and I'd like to know if this topic has progressed.)

A: 

Check out Object serialization here:

Encoding/Decoding Objects (apple.com)

Basically, you have to make your classes Key-Value Coding compliant, to properly save all of your data; It archives them into binary property lists. After you write your initWithCoder: and encodeWithCoder: functions it's pretty much automatic!

Jeffrey Forbes
Key-Value Coding and NSCoding are two separate concepts.
Jon Hess
+3  A: 

You need to make all of the classes you want to serialize implement the NSCoding protocol. After that, you need to encode them with the NSKeyedArchiver class. That class will recursively serialize your objects, and will deal with cycles. NSKeyedArchiver is available in all releases of the iPhone SDK. To decode your objects, you'll uses NSKeyedUnarchiver.

Jon Hess
Will it maintain the references between objects? Say an object in a collection has a pointer to another object in another collection, will that pointer still be there after the objects are decoded?
Steph Thirion
Yes, it handles multiple references, and cycles. You just need to make sure all of the objects implement initWithCoder:, and encodeWithCoder: from the NSCoding protocol. The most common place where this is used in Cocoa is NIB files. Interface Builder creates your Interface as instances of the AppKit classes, and then archives them with an NSCoder.
Jon Hess
It works like a charm. I had been misguided for months because of the answer to my similar question. Thanks for clearing that up, that's a real life changer, and also a lesson to not believe anything people with reputation say on stackoverflow. :)
Steph Thirion