Using 'self'?


#1

Okay I’m not entirely sure I understand the concept of using self. or what exactly he meant in that snippet at the top of page 106. “… they never read or write to an instance variable except using its accessor method.”

Just below that is an example. Now my brain works like a computer program so I need to know step by step exactly what is happening here and I mentally error out when this method calls itself.

-(float)bodyMassIndex { float h = [self heightInMeters]; return [self weightInKilos] / h * h; }

So, height in meters is called… again, because main.c already called it once and set it to 97. then called the bodyMassIndex method right? (i think its a method) anyhow, so this method goes out again to get height in meters and saves it to h. so what is the self actually doing and whats the point? why not leave it the way it was before all the convoluted self stuff came in?


#2

Relax and go and read that paragraph again, a couple of times, with an open mind.

self is a pre-defined variable, that the Objective-C Language makes available inside a method: it refers to the object on which the method has been invoked. Since the method can be either a class method or an instance method, the kind of object that self refers to will be different. In a class method, self refers to the class object itself (this is a singleton object and represents the class itself; its name is the same as the name of the class), and in an instance method self refers to the object instance created from the class.

A program can have several objects, each an instances of some class type. It is through self that a method has access to an object and thus can access its instance variables or invoke methods on the object.

Inside a method, you can access an instance variable of the object directly (for example: heightInMeters or using the explicit pointer syntax self->heightInMeters) or indirectly through self by invoking its accessor method (for example: [self heightInMeters].) (As you gain more experience, you will get to appreciate the difference.)

Accessing through self:

-(float)bodyMassIndex
{
     float h = [self heightInMeters];        // accessing directly
     return [self weightInKilos] / h * h;
}

Accessing directly:

-(float)bodyMassIndex
{
     float h = heightInMeters;     // accessing directly bypasses the hidden machinery
     return weightInKilos / h * h;
}

Accessing directly (another variant):

-(float)bodyMassIndex
{
     float h = self->heightInMeters;     // accessing directly bypasses the hidden machinery
     return self->weightInKilos / h * h;
}

Although accessing instance variables directly can be more efficient, doing so bypasses the hidden machinery which you will get to learn if you persist and continue on the path you have started. (The hidden machinery is triggered by the accessor method invocations.)


#3

Thank you for the quick response. I appreciate the patience. That does help clear things up a little.