self

Inside any method, you have access to the implicit local variable self. self is a pointer to the object that is running the method. It is used when an object wants to send a message to itself. For example, many Objective-C programmers are quite religious about accessor methods; they never read or write to an instance variable except using its accessor methods. Update your bodyMassIndex method to please the purists:

-​ ​(​f​l​o​a​t​)​b​o​d​y​M​a​s​s​I​n​d​e​x​
{​
 ​ ​ ​ ​f​l​o​a​t​ ​h​ ​=​ ​[​s​e​l​f​ ​h​e​i​g​h​t​I​n​M​e​t​e​r​s​]​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​[​s​e​l​f​ ​w​e​i​g​h​t​I​n​K​i​l​o​s​]​ ​/​ ​(​h​ ​*​ ​h​)​;​
}​

Here an instance of Person sends itself two messages, heightInMeters and weightInKilos, to get the values of its instance variables.

You can also pass self as an argument to let other objects know where the current object is. For example, your Person class might have a method addYourselfToArray: that would look like this:

-​ ​(​v​o​i​d​)​a​d​d​Y​o​u​r​s​e​l​f​T​o​A​r​r​a​y​:​(​N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​*​)​t​h​e​A​r​r​a​y​
{​
 ​ ​ ​ ​[​t​h​e​A​r​r​a​y​ ​a​d​d​O​b​j​e​c​t​:​s​e​l​f​]​;​
}​

Here you use self to tell the array where the instance of Person lives. It is literally its address.

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

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