12. Properties

One of the most common programming tasks is to set or retrieve a value held in one of an object’s instance variables. Although it is possible in some cases to access the instance variable directly, doing so is a bad practice. The correct way to access an instance variable is to write accessor methods. An accessor method that sets an instance variable’s value is called a setter and one that returns an instance variable’s value is called a getter.

For example, if your object has integer instance variable numberOfDogs, you should declare and implement the following two methods:

-(int) numberOfDogs; // returns the current value

-(void) setNumberOfDogs:(int) newNumberOfDogs; // sets a new value

Note

Naming the getter instanceVariableName ...

Get Learning Objective-C 2.0: A Hands-On Guide to Objective-C for Mac and iOS Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.