• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Objective C language question: Making init like a constructor
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Objective C language question: Making init like a constructor


  • Subject: Re: Objective C language question: Making init like a constructor
  • From: Aram Greenman <email@hidden>
  • Date: Sun, 26 May 2002 03:17:19 -0700

On Saturday, May 25, 2002, at 02:53 PM, Michael Gersten wrote:

The basic question: Is it possible to design a runtime so that init's can act like constructors?

The details:
In C++, (I'm not sure about Java), when you are creating a new object, it first has an ISA of the root class, and the root class's constructor run; then the ISA is changed to the next class, and that class's constructor is run, etc.

In Objective C, the ISA is always the lowest class, even while the [super init]'s are running; this means that any message sent by those upper classes during init may wind up going down into a subclass that hasn't been initialized yet.

<snip>

You could get a concrete method implementation for the message, and invoke that instead of sending the message. See +[NSObject instanceMethodForSelector:], -[NSObject methodForSelector:].

@implementation Foo
- (id)init {
if (self = [super init]) {

// to avoid override by a subclass, invoke method directly
// instead of sending message

void (*imp)(id, SEL);
imp = (void (*)(id, SEL))[[Foo class] instanceMethodForSelector:@selector(bar)];

imp(self, @selector(bar));
}
return self;
}
@end

One problem here is that if -[Foo bar] sends any messages to self those messages will still invoke the method of the subclass. Plus the tedium of all those function pointers.

You _could_ just change isa, and then change it back, although there might be a good reason not to do that.

@implementation Foo
- (id)init {
if (self = [super init]) {

Class cls = [self class];

self->isa = [Foo class];

// send messages to self

self->isa = cls;
}
return self;
}
@end



Aram
_______________________________________________
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.

  • Follow-Ups:
    • isa
      • From: Aram Greenman <email@hidden>
References: 
 >Objective C language question: Making init like a contrustor (From: Michael Gersten <email@hidden>)

  • Prev by Date: Re: Objective C language question: Making init like a contrustor
  • Next by Date: Re: Absolute Paths
  • Previous by thread: Re: Objective C language question: Making init like a contrustor
  • Next by thread: isa
  • Index(es):
    • Date
    • Thread