Inheritance hierarchy

All objects inherit (either directly or indirectly) from NSObject:

Figure 20.3  Inheritance diagram of some classes you know

Inheritance diagram of some classes you know

NSObject has many methods but only one instance variable: the isa pointer. Every object’s isa pointer points at the class that created it. (Get it? When you have a BNRPerson instance, that object is a BNRPerson. When you have an NSString instance, that object is a[n] NSString.)

Figure 20.4  Every object knows which class created it

Every object knows which class created it

When you send a message to an object, you kick off a search for a method of that name. The search follows the object’s isa pointer to start looking for the method in the object’s class. If there is no method of that name there, then it is on to the superclass. The hunt stops when the method is found or when the top of the hierarchy (NSObject) is reached.

Let’s say that you send the message fido to an object. To respond to this message, the object uses the isa pointer to find its class and ask, Do you declare an instance method named fido?

If the class has a method named fido, it gets executed. If the class does not have a fido method, it asks its superclass, Do you declare an instance method named fido?

And up, up the hierarchy it goes on the hunt for the implementation of a method named fido. The hunt stops when the method is found or when the top of the hierarchy is reached.

Figure 20.5  Object diagram for BMITime

Object diagram for BMITime

At the top of the hierarchy, NSObject says, Nope, no fido method. At this point, you get an error message that says something like, -[BNREmployee fido]: unrecognized selector sent to instance 0x100106e102. This can be translated as, There is no instance method of this name defined anywhere in this object’s inheritance hierarchy.

The first implementation that is found is the one that gets executed. BNREmployee and BNRPerson both have implementations of bodyMassIndex, but if a BNREmployee is sent the bodyMassIndex message, the implementation in BNREmployee will be found first and executed. The hunt ends before reaching the BNRPerson class.

When you use the super directive, you are sending a message to the current object but saying, Run a method with this name, but start the search for its implementation at your superclass.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset