Which Method Is Selected?

We covered how the system searches up the hierarchy for a method to apply to an object. If you have methods in different classes with the same name, the correct method is chosen based on the class of the receiver of the message. Program 8.7 uses the same class definition for ClassA and ClassB as before.

Program 8.7

#import <Foundation/Foundation.h>// insert definitions for ClassA and ClassB hereint main (int argc, char * argv[]){   @autoreleasepool {      ClassA  *a = [[ClassA alloc] init];      ClassB  *b = [[ClassB alloc] init];      [a initVar];   // uses ClassA method      [a printVar];  // reveal value of x;      [b initVar];   // use overriding ClassB method      [b printVar];  // ...

Get Programming in Objective-C, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.