modifying self in init
modifying self in init
- Subject: modifying self in init
- From: Mike Bolton <email@hidden>
- Date: Wed, 15 Sep 2004 02:08:21 -0400 (EDT)
I'm wondering if anyone can help me with the following
problem:
I have a superclass, A, and a subclass, B. I've
created a special init routine for class A, called
initWithPath, which sets a few of the ivars of the
superclass, such as the fileName, etc. Now, there are
two (or more) different types of files that may be
passed to the init routine, but the file type cannot
be determined until the header for the file has been
read. Anyways, if the file is of type 1, I want the
initWithPath routine of A to set the ivars as usual,
and return an object of type A (in this case, simply
return self). Now, if the file is of type 2, I want
the ivars in the superclass to be set to the same
values, but an object of type B should be returned.
One way I thought of accomplishing this is to do
something like this:
@implementation A
- (id) initWithPath:(NSString *)path
{
if (self = [super init])
{
//read header of file
if (fileType == 2)
{
[self release];
self = [[B alloc] init]; //maybe I need a
retain here?
}
[self setFilename:path];
ivar1 = blah;
ivar2 = bleh;
etc.
}
return self;
}
@end
this seems to work, although I'm not sure if modifying
what self points to is a good idea. The other
solution would be to have something like:
@implementation A
- (id) initWith...
{
id object = self;
if (object = [super init])
{
blah blah
if (fileType == 2)
{
[self release];
object = [[B alloc] init];
}
[object setFilename:path];
[object setIvar1:blah];
[object setIvar2:bleh];
}
return object;
}
the problem with the second implementation is that I
need to create setter methods for each ivar I want to
assign values to (not a big deal, but the first
implementation was able to avoid this). Although a
solution to this would be to create another method
which is responsible for setting the default values of
the objects, although this is normally what the init
routine is responsible for.
Anyways, if anyone can give me any advice or
suggestions on how to properly implement this, I would
greatly appreciate it. I've searched the list
archives for similar problems, but I didn't find any
messages which addressed modifying the value of self.
Thanks in advance,
Mike
______________________________________________________________________
Post your free ad now! http://personals.yahoo.ca
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden