Re: Archiving objects without their owner[1]
Re: Archiving objects without their owner[1]
- Subject: Re: Archiving objects without their owner[1]
- From: Dan Bernstein <email@hidden>
- Date: Fri, 21 Dec 2001 00:54:11 +0200
Thanks, Chris.
This actually works. I'm still wondering about -[NSUnarchiver
replaceObject:withObject] though. Is there any context in which it works
as advertised?
-- Dan
On Friday, December 21, 2001, at 12:03 AM, Chris Kane wrote:
On Tuesday, December 18, 2001, at 01:19 PM, Dan Bernstein wrote:
What I'm trying to do is basically what (I think) AppKit does with nib
files:
I want to archive an object graph in which multiple objects point to
some "owner" object. I don't want the owner (and the graph rooted at
it) to be archived. When unarchiving, I want everything that pointed
to the "owner" to point to an object I supply.
I guess I should use [NSArchiver replaceObject:withObject:] to archive
some "dummy" "placeholder" instead of the owner when archiving. It's
just that it isn't clear when I'm supposed to do when unarchiving, in
particular - what should be the first argument to [NSUnarchiver
replaceObject:withObject:].
The way to hook this into the archiving framework is to implement
-replacementObjectForArchiver: on the owner object class to return an
instance of a placeholder type class you create for this purpose.
Obviously, do NOT put a -replacementObjectForArchiver: method on any
class which you do not own, since you will change the archiving
behavior for the whole class and subclasses. The assumption here is
that the "owner" is a class you've created, which never needs to be
archived normally.
In the -encodeWithCoder: of the placeholder class, you don't need to
encode anything, probably. In the -initWithCoder: method, release self
and return an instance of the owner class you want on unarchive.
The only "trick" then is that this placeholder class has to have a way
to get a hold of an instance, the SAME instance, of the new owner
class, every time the placeholder's -initWithCoder: is called. This
could be done by having the placeholder class keep track of one in a
static variable (possibly with some way to reset that variable to nil,
if you need to unarchive several times with different owners). Or a
typical way is to put a +[FooOwner +sharedFooOwner] method on the owner
class (FooOwner) which keeps a singleton.
Chris Kane
Cocoa Frameworks, Apple