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:
int main(int argc, const char * argv[]) { @autoreleasepool { // Create an instance of BNRPerson BNRPerson *mikey = [[BNRPerson alloc] init]; // Give the instance variables interesting values using setters [mikey setWeightInKilos:96]; [mikey setHeightInMeters:1.8]; mikey.weightInKilos = 96; mikey.heightInMeters = 1.8; // Log the instance variables using the getters float height = [mikey heightInMeters]; int weight = [mikey weightInKilos]; float height = mikey.heightInMeters; int weight = mikey.weightInKilos; NSLog(@"mikey is %.2f meters tall and weighs %d kilos", height, weight); // Log some values using custom methods float bmi = [mikey bodyMassIndex]; NSLog(@"mikey has a BMI of %.2f", bmi); } return 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:
mikey.weightInKilos = 96; [mikey setWeightInKilos:96];
and these two lines do the exact same thing:
float w = mikey.weightInKilos; float w = [mikey weightInKilos];
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.