Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSCoder vs NSDictionary, when do you use what?

Tags:

cocoa

I'm trying to figure out how to decide when to use NSDictionary or NSCoder/NSCoding?

It seems that for general property lists and such that NSDictionary is the easy way to go that generates XML files that are easily editable outside of the application.

When dealing with custom classes that holds data or possibly other custom classes nested inside, it seems like NSCoder/NSCoding would be the better route since it will step through all the contained object classes and encode them as well when an archive command is used.

NSDictionary seems like it would take more work to get all the properties or data characteristics to a single level to be able to save it, where as NSCoder/NSCoding would automatically encode nested custom classes that implement the NSCoding interface.

Outside of it being binary data and not editable outside of your application is there a real reason to use one over the other? And along those lines is there an indicator of which way you should lean between the two? Am I missing something obvious?

like image 251
crackity_jones Avatar asked Sep 29 '08 14:09

crackity_jones


1 Answers

Apple's documentation on object graphs has this to say:

Mac OS X serializations store a simple hierarchy of value objects, such as dictionaries, arrays, strings, and binary data. The serialization only preserves the values of the objects and their position in the hierarchy. Multiple references to the same value object might result in multiple objects when deserialized. The mutability of the objects is not maintained.

Mac OS X archives store an arbitrarily complex object graph. The archive preserves the identity of every object in the graph and all the relationships it has with all the other objects in the graph. When unarchived, the rebuilt object graph should, with few exceptions, be an exact copy of the original object graph.

The way I interpret this is that, if you want to store simple values, serialization (using an NSDictionary, for example) is a fine way to go. If you want to store an object graph of arbitrary types, with uniqueness and mutability preserved, using archives (with NSCoder, for example) is your best bet.

You may also want to read Apple's Archives and Serializations Programming Guide for Cocoa, of which the aforelinked page on object graphs is a part, as it covers this topic well.

like image 154
Evan DiBiase Avatar answered Sep 21 '22 15:09

Evan DiBiase