Search code examples
objective-cinheritancemessageself

Simple inheritance question in Objective-C


I have two Objective-C classes and one is derived from the other as

@interface DerivedClass : BaseClass
{
}

The code section below belongs to BaseClass:

- (id)init {
    if (self = [super init]) {
       [self configure]; 
    }   
    return self;
}

- (void) configure{} //this is an empty method

And the code section belongs to the DerivedClass:

-(void) configure{
    NSLog(@"derived configure called");
}

Now, when I say derivedInstance = [DerivedClass new]; and watch the call stack, I see that the configure method of my derived class gets called at the [self configure] line of the base's init method.

I'm an Objective-C noob and I'm confused about how a method of a derived class gets called from the method of a base class. "self" keyword is explained to be the same thing as "this" keyword of some languages but I think this explanation is not completely correct, right?


Solution

  • [self someMessage] will send the message "someMessage" to the current object, which is an instance of DerivedClass.

    Message dispatch is done dynamically at run-time, so it will behave as whatever the object is at that time.