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 the integer instance variable numberOfDogs
, you should declare and implement the following two methods:
// returns the current value-(NSInteger) numberOfDogs; // sets a new value-(void)setNumberOfDogs:(NSInteger) newNumberOfDogs; ...
Get Learning Objective-C 2.0: A Hands-on Guide to Objective-C for Mac and iOS Developers, Second Edition 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.