1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Encoding vs Array and Dictionary

Discussion in 'Mac Programming' started by nashyo, Dec 18, 2011.

  1. macrumors 6502

    nashyo

    #1
    I'm currently being introduced slowly to encoding in Objective C, and I have a fundamental question to ask.

    Why would an Object orientated programmer want to encode an object to the file system, instead of create an array or dictionary of objects?

    I know there's a sensible answer to this, so please don't think I'm contesting the logic of it.

    Thanks
    Rob
     
  2. macrumors 6502a

    #2
  3. macrumors 68030

    jared_kipe

    #3
    Are you asking why would someone want to "save" an object to load again later?
     
  4. macrumors 68040

    #4
    I was wondering the same thing.

    "Why would an Object orientated programmer want to encode an object to the file system"

    Sounds like archiving an object to disk.
     
  5. macrumors 68000

    Sydde

    #5
    The way encoding works, the NSKeyedArchiver asks the root object to encode itself. If the root object's -encodeWithCoder: method involves encoding any objects it owns (ivars), they will be encoded into the graph, and any objects those own or reference will be encoded recursively until the entire logical content of the root object is mapped. One advantage would be that no object is encoded more than once, the archiver just encodes cross-references. All this goes into a data object in the form of a binary plist which can then be written to a file or stored in a user defaults entry.

    If the complementary -decodeWithCoder: methods are written correctly, NSKeyedUnarchiver can restore the entire object graph using the data object that was archived. This technique allows a much richer and more complex structure to be saved and restored easily and efficiently than you might be able to do with an array or dictionary. Once decoded, you program state is essentially fully restored to what it was when you saved it (except, usually, without the undo stack).

    If you look at the documentation for NSArray or NSDictionary, you will see that there are strict limitations on what they can write to a file; encoding lets you get around these limitations.
     
  6. macrumors 6502

    nashyo

    #6
    Got it

    Thanks for all the responses.

    Sydde you answered that really well.
     

Share This Page