Dot notation

Objective-C programmers call accessor methods a lot. When properties were introduced, Apple also introduced a shorthand dot notation for calling those accessors.

Many Objective-C programmers prefer dot notation because it is easier to type. In main.m, try out dot notation:

i​n​t​ ​m​a​i​n​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​@​a​u​t​o​r​e​l​e​a​s​e​p​o​o​l​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​C​r​e​a​t​e​ ​a​n​ ​i​n​s​t​a​n​c​e​ ​o​f​ ​B​N​R​P​e​r​s​o​n​
 ​ ​ ​ ​ ​ ​ ​ ​B​N​R​P​e​r​s​o​n​ ​*​m​i​k​e​y​ ​=​ ​[​[​B​N​R​P​e​r​s​o​n​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​G​i​v​e​ ​t​h​e​ ​i​n​s​t​a​n​c​e​ ​v​a​r​i​a​b​l​e​s​ ​i​n​t​e​r​e​s​t​i​n​g​ ​v​a​l​u​e​s​ ​u​s​i​n​g​ ​s​e​t​t​e​r​s​
 ​ ​ ​ ​ ​ ​ ​ ​[​m​i​k​e​y​ ​s​e​t​W​e​i​g​h​t​I​n​K​i​l​o​s​:​9​6​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​[​m​i​k​e​y​ ​s​e​t​H​e​i​g​h​t​I​n​M​e​t​e​r​s​:​1​.​8​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​m​i​k​e​y​.​w​e​i​g​h​t​I​n​K​i​l​o​s​ ​=​ ​9​6​;​
 ​ ​ ​ ​ ​ ​ ​ ​m​i​k​e​y​.​h​e​i​g​h​t​I​n​M​e​t​e​r​s​ ​=​ ​1​.​8​;​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​L​o​g​ ​t​h​e​ ​i​n​s​t​a​n​c​e​ ​v​a​r​i​a​b​l​e​s​ ​u​s​i​n​g​ ​t​h​e​ ​g​e​t​t​e​r​s​
 ​ ​ ​ ​ ​ ​ ​ ​f​l​o​a​t​ ​h​e​i​g​h​t​ ​=​ ​[​m​i​k​e​y​ ​h​e​i​g​h​t​I​n​M​e​t​e​r​s​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​i​n​t​ ​w​e​i​g​h​t​ ​=​ ​[​m​i​k​e​y​ ​w​e​i​g​h​t​I​n​K​i​l​o​s​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​f​l​o​a​t​ ​h​e​i​g​h​t​ ​=​ ​m​i​k​e​y​.​h​e​i​g​h​t​I​n​M​e​t​e​r​s​;​
 ​ ​ ​ ​ ​ ​ ​ ​i​n​t​ ​w​e​i​g​h​t​ ​=​ ​m​i​k​e​y​.​w​e​i​g​h​t​I​n​K​i​l​o​s​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​m​i​k​e​y​ ​i​s​ ​%​.​2​f​ ​m​e​t​e​r​s​ ​t​a​l​l​ ​a​n​d​ ​w​e​i​g​h​s​ ​%​d​ ​k​i​l​o​s​"​,​ ​h​e​i​g​h​t​,​ ​w​e​i​g​h​t​)​;​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​L​o​g​ ​s​o​m​e​ ​v​a​l​u​e​s​ ​u​s​i​n​g​ ​c​u​s​t​o​m​ ​m​e​t​h​o​d​s​
 ​ ​ ​ ​ ​ ​ ​ ​f​l​o​a​t​ ​b​m​i​ ​=​ ​[​m​i​k​e​y​ ​b​o​d​y​M​a​s​s​I​n​d​e​x​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​m​i​k​e​y​ ​h​a​s​ ​a​ ​B​M​I​ ​o​f​ ​%​.​2​f​"​,​ ​b​m​i​)​;​

 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

This notation looks just like the notation used for accessing the members of a struct. It is critical to remember, however, that when using dot notation with an object, a message is being sent.

These two lines do the exact same thing:

m​i​k​e​y​.​w​e​i​g​h​t​I​n​K​i​l​o​s​ ​=​ ​9​6​;​
[​m​i​k​e​y​ ​s​e​t​W​e​i​g​h​t​I​n​K​i​l​o​s​:​9​6​]​;​

and these two lines do the exact same thing:

f​l​o​a​t​ ​w​ ​=​ ​m​i​k​e​y​.​w​e​i​g​h​t​I​n​K​i​l​o​s​;​
f​l​o​a​t​ ​w​ ​=​ ​[​m​i​k​e​y​ ​w​e​i​g​h​t​I​n​K​i​l​o​s​]​;​

Notice that mikey.weightInKilos sends one of two possible messages, depending on the context in which it is being used. That is, it calls either the getter method (weightInKilos) or the setter method (setWeightInKilos:) depending on whether it is being used to get or set mikey’s _weightInKilos.

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

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