Custom Getters and Setters

In another variation, sometimes you do not want the default getters and setters generated by the compiler. As an example, suppose you want self.fuelAmount to return liters instead of gallons, but only if a new property, showLiters, is YES. You also want to access this new property using isShowingLiters.

It only takes one line in Car.h to add the property. Add the following code below the existing properties:

@property (getter = isShowingLiters) BOOL showLiters;

The qualifier sets a different name for the getter. Instead of using aCar.showLiters to check the value of the variable, you use aCar.isShowingLiters, a more descriptive name. Setting the value still uses aCar.showLiters:

if (aCar.isShowingLiters) ...

Get Learning iOS Development: A Hands-on Guide to the Fundamentals of iOS Programming 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.