Re: NSDocument Default Contents
Re: NSDocument Default Contents
- Subject: Re: NSDocument Default Contents
- From: James Quick <email@hidden>
- Date: Mon, 14 Jul 2003 22:55:09 -0400
On Monday, July 14, 2003, at 07:52 PM, The Amazing Llama wrote:
I'm implementing an NSDocument subclass, which is simple enough.
I know that if I want to make something happen in all documents, new
or opened, I put that code in -init.
If I want it to take place only in opened documents, the code goes in
-initWithContentsOfFile:
Where should I put code that should fill a new document with 'default'
data? Should I put it in -init, and then erase it in
-initWithContentsOfFile? That seems a little kludgey.
Better ideas?
Look at it from a slightly different angle. Rather dividing active
responsibility
among the initialization methods, think instead about a chain of init
messages
which add information rather then implement behavior. Do work at a
point when
you know enough. That point becomes the designated initializer.
(Yes, sometimes one implements more than one designated inializer, but
usually
that is neither required nor desired).
- (id)initWithContentsOfFile:(NSString *)fileName ofType:(NSString *)
docType;
You've got 2 NSStrings to play with here. You might reserve a doctype
(or
even a substring of doctype) to specify the generation of 'default'
data.
If appropriate, you might use an empty or nil fileName to trigger it.
If -init, by default, returns a new document, initialized with the
'default' data,
then it's definition is something like. In this case I'm assuming a nil
object
passed as fileName to signal default data is desired.
- init
{
return [initWithContentsOfFile: nil ofType:(NSString *) @"someType";
}
and the designated intializer looks something like:
- (id)initWithContentsOfFile:(NSString *)fileName ofType:(NSString *)
docType;
{
if ((self = [super init])) {
if (fileName == nil) {
// generate data, or just say what document contains it.
fileName = [somethingWhichReturnsA:
@"/full/path/to/defaultDataFile"];
}
// Now your common code to initialize the document from either
defaults
// or from a file previously saved by user.
}
return self;
}
Since -init is not the designated initializer it is not responsible for
creating anything.
It's responsibility is simply to indicate the result when nothing else
has been specify.
It feeds the designated initializer with information about what is
desired. I rarely
think about -init as a destination method, one which performs
significant work.
Instead I think of it as the beginning of a chain of messages which
always ends
at a designated initializer. The flow of messages passes from the
indefinite
to the specific, with each link specifying a new 'default' behavior.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.