Search code examples
objective-cmacoscocoa-design-patternsnscodingnscoder

How do NSCoder and/or NSKeyedUnarchiver handle multiple decodings of the same object?


I was wondering how NSCoder would handle an object that was shared and encoded by multiple objects the next time it was decoded. Will it make two copies of the object, or will one object be decoded and shared between all other objects that decode it?

I've provided a small example of a situation like this below.

Example:

  1. Application starts up
  2. Object A and Object B set Object C as their delegate
  3. Application receives termination notification.
  4. Object A and Object B encode themselves and all of their objects (including their delegates)
  5. Application shuts down and restarts
  6. Object A and Object B decode themselves and all of their objects (including their delegates)

Would Object A and Object B both share the same decoded object after step 6 or would they each have their own copy of it?


Solution

  • They'll share a reference to the same object (unless you go to lengths to change that behavior).

    I.e. NSCoding can deal with fully cyclic, omni-directional, complexly connected, object graphs (as long as all graph participants correctly support NSCoding).

    Note that encoding delegates is highly atypical. Delegates are usually connected to an unarchived object graph after anarchival and delegates act as a sort of conduit between your archived model layer (or archived view layer, in the case of IB -- the story is more complex, really, for XIB files... but... close enough) and the rest of your app.