Re: semantics of init
Re: semantics of init
- Subject: Re: semantics of init
- From: email@hidden (Andrew Demkin)
- Date: Tue, 3 Jun 2003 21:14:14 -0700
At 8:11 PM 6/3/03, Andrew Pinski wrote:
>
At 8:02 PM 6/3/03, Niko Matsakis wrote:
>
> For example, suppose I extend SomeClass with SomeOtherClass, should I
>
> do something like this in the constructor?
>
>
>
> - (void) init
>
> {
>
> id me = [super init];
>
> me->myfields = some_data;
>
> return me;
>
> }
>
>
>
> as opposed to
>
>
>
> - (void) init
>
> {
>
> [super init];
>
> myfields = some_data;
>
> return self;
>
> }
>
>
Even better (like the first one but also like the second one)
>
>
- (void) init
>
{
>
if ((self = [super init]) != NULL)
>
{
>
myfields = some_data;
>
}
>
return self;
>
}
If you want to be even safer, you should probably do something like this:
self = [super init];
if ([self isKindOfClass: [MyClass class]])
{
/* access MyClass instance vars here */
}
return self;
Otherwise, if [super init] were to return some object that doesn't have the
same memory layout as your own class, writing to your instance variables
would have undefined behavior (possibly causing a memory corruption or
crash).
I'm unsure whether there is any code which overrides an -init method in
this way (it's obviously not advisable), but the fact that Objective-C
allows it probably means there's someone out there who's going to be clever
and try it. As the original poster pointed out, anyone doing so should at
least make it well-documented.
For those paying close attention, even the above may not be safe if the
object returned from [super init] were an already-initialized instance of
MyClass (or one of it's subclasses) because it could initialize the object
twice.
In short, re-assigning 'self' and permitting the return of arbitrary
objects from 'init' might sometimes seem useful, but it definitely raises
the bar for writing robust code.
HTH,
Andrew.
_______________________________________________
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.