Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book


Properties expose class variables and methods to outside use through what are called “accessor methods” (that is, methods that access information). Using properties might sound redundant. After all, the class definition shown in Listing 3-1 already announces public methods. So why use properties? It turns out that there are advantages to using properties over hand-built methods, not the least of which are dot notation and memory management.

Dot Notation

Dot notation allows you to access object information without using brackets. Instead of calling [myCar year] to recover the year instance variable, you use myCar.year. While this may look as if you’re directly accessing the year instance variable, you’re not. Properties always invoke methods. These, in turn, can access an object’s data. So you’re not, strictly speaking, breaking an object’s encapsulation as properties rely on these methods to bring data outside the object.

Due to method hiding, properties simplify the look and layout of your code. For example, you can access properties to set a table’s cell text via

myTableViewCell.textLabel.text = @"Hello World";

rather than the more cumbersome

[[myTableViewCell textLabel] setText:@"Hello World"];

The property version of the code is more readable and ultimately easier to maintain. Admittedly, Objective C 2.0’s dot notation may initially confuse C programmers who are used to using dots for structures instead.

Properties and Memory Management

Properties can help simplify memory management. You can create properties that automatically retain instance variables for the lifetime of your objects and release them when you set those variables to nil. Setting a retained property ensures that memory will not be released until you say so. Of course, properties are not a magic bullet. They must be defined and used properly.

Assigning an object to a retained property means you’re guaranteed that the objects will be available throughout the tenure of your ownership. Listing 3-2 did not retain its make and model. If those objects were released somewhere else in an application, the pointers to the memory that stored those objects would become invalid. At some point, the application might try to access that memory and crash. By retaining objects, you ensure that the memory pointers remain valid.

The arrayWithObjects: method normally returns an autoreleased object, whose memory is deallocated at the end of the event loop cycle. (See Chapter 1, “Introducing the iOS SDK,” for details about autorelease pools. A deeper discussion about memory management follows later in this chapter.) Assigning the array to a retained property means that the array will stick around indefinitely. You retain the object, preventing its memory from being released until you are done using it.

self.colors = [NSArray arrayWithObjects:
    @"Gray", @"Silver", @"Black", nil];

When you’re done using the array and want to release its memory, set the property to nil. This approach works because Objective-C knows how to synthesize accessor methods, creating properly managed ways to change the value of an instance variable. You’re not really setting a variable to nil. You’re actually telling Objective-C to run a method that releases any previously set object and then sets the instance variable to nil. All this happens behind the scenes. From a coding point of view, it simply looks as if you’re assigning a variable to nil.

self.colors = nil;

Do not send release directly to retained properties (for example, [self.colors release]). Doing so does not affect the colors instance variable assignment, which now points to memory that is likely deallocated. When you next assign an object to the retained property, the memory pointed to by self.colors will receive an additional release message, likely causing a double-free exception.

Creating Properties

There are two basic styles of properties: read-write and read-only. Read-write properties, which are the default, let you modify the values you access; read-only properties do not. Use read-only properties for instance variables that you want to expose, without providing a way to change their values. They are particularly handy for properties that are generated by algorithm from several instance variables or from device sensors, such as a device orientation.

The two kinds of accessor methods you must provide are called setters and getters. Setters set information; getters retrieve information. You can define these with arbitrary method names or you can use the standard Objective-C conventions: The name of the instance variable retrieves the object, while the name prefixed with “set” sets it. Objective-C can even synthesize these methods for you. For example, if you declare a property such as the Car class’s year in your class interface, as such

@property (assign) int year;

and then synthesize it in your class implementation with

@synthesize year;

you can read and set the instance variable with no further coding. Objective-C builds two methods that get the current value (that is, [myCar year]) and sets the current value (that is, [myCar setYear:1962]) and adds the two dot notation shortcuts:

myCar.year = 1962;
NSLog(@"%d", myCar.year);

To build a read-only property, declare it in your interface using the readonly attribute. Read-only properties use getters without setters. For example, here’s a property that returns a formatted text string with car information:

@property (readonly) NSString *carInfo;

Although Objective-C can synthesize read-only properties, you can also build the getter method by hand and add it to your Class implementation. This method returns a description of the car via stringWithFormat:, which uses a format string ala sprintf to create a new string:

- (NSString *) carInfo
    return [NSString stringWithFormat:
        @"Car Info\n    Make: %@\n    Model: %@\n    Year: %d",
        self.make ? self.make : @"Unknown Make",
        self.model ? self.model : @"Unknown Model",

This method now becomes available for use via dot notation. Here’s an example:


If you choose to synthesize a getter for a read-only property, you should use care in your code. Inside your implementation file, make sure you assign the instance variable for that property without dot notation. Imagine that you declared model as a read-only property. You could assign model with

model = @"Prefect";

but not with

self.model = @"Prefect";

The latter use attempts to call setModel:, which is not defined for a read-only property.

Creating Custom Getters and Setters

Although Objective-C automatically builds methods when you @synthesize properties, you may skip the synthesis by creating those methods yourself. For example, you could build methods as simple as the following. Notice the capitalization of the second word in the set method. By convention, Objective-C expects setters to use a method named setInstance:, where the first letter of the instance variable name is capitalized.

-(int) year
    return year;

- (void) setYear: (int) aYear
    year = aYear;

When building your own setters and getters, you might add some basic memory management. The following methods retain new items and release previous values:

- (NSString *) model
    return model;

- (void) setModel: (NSString *) newModel
    if (newModel != model) {
        [model release];
        model = [newModel retain];

You could go even further by building more complicated routines that generate side effects upon assignment and retrieval. For example, you might keep a count of the number of times the value has been retrieved or changed, or send in-app notifications to other objects. The Objective-C compiler remains happy so long as it finds, for any property, a getter (typically named the same as the property name) and a setter (usually setName:, where Name is the name of the property). What’s more, you can bypass any Objective-C naming conventions by specifying setter and getter names in the property declaration. This declaration creates a new Boolean property called forSale and declares a custom getter/setter pair. As always, you add any property declarations to the class interface:

@property (getter=isForSale, setter=setSalable:) BOOL forSale;

Then you synthesize the methods as normal in the class implementation. The implementation is typically stored in the .m file that accompanies the .h header file.

@synthesize forSale;

If you have more than one item to synthesize, you can add them in separate @synthesize statements or combine them onto a single line, separating each by a comma:

@synthesize forSale, anotherProperty, yetAnotherProperty;

Using this approach creates both the normal setter and getter via dot notation plus the two custom methods, isForSale and setSalable:. Oddly, while you can use dot notation to assign and retrieve forSale, you cannot use the equivalent methods, and you cannot use the customized setter in dot notation. Here is how the usage breaks down:

Car *myCar = [Car car];

// You can use the synthesized setter and getter of course
[myCar setSalable:YES];
printf("The car %s for sale\n",
    myCar.isForSale ? "is" : "is not");

// The normal getter and setter still work in dot notation
myCar.forSale = NO;
printf("The car %s for sale\n",
    myCar.forSale ? "is" : "is not");

// But not the method versions.
// These produce run-time errors
// [myCar setForSale:YES];
// printf("The car %s for sale\n",
//     [myCar forSale] ? "is" : "is not");

// You cannot use the customized setter via dot notation.
// This produces a compile-time error
// myCar.setSalable = YES;

Property Attributes

In addition to read-write and read-only attributes, you can specify whether a property is retained and/or atomic. The default behavior for properties is assign. Assignment acts exactly as if you’d assigned a value to an instance variable. There’s no special retain/release behavior associated with the property, but by making it a property you expose the variable outside the class via dot notation. A property that’s declared

@property NSString *make;

uses the assign behavior.

Setting the property’s attribute to retain does two things. First, it retains the passed object upon assignment. Second, it releases the previous value before a new assignment is made. Using the retain attribute introduces the memory management advantages discussed in the previous section. To create a retained property, add the attribute between parentheses in the declaration:

@property (retain) NSString *make;

A third attribute called copy sends copies the passed object and releases any previous value. Copies are always created with a retain count of 1.

@property (copy) NSString *make;

You can also retain the object as you assign it, as shown here:

myCar.make = @"Ford";
[myCar.make retain];

When you develop in a multithreaded environment, you want to use atomic methods. Xcode synthesizes atomic methods to automatically lock objects before they are accessed or modified and unlock them after. This ensures that setting or retrieving an object’s value is performed fully regardless of concurrent threads. There is no atomic keyword. All methods are synthesized atomically by default. You can, however, state the opposite, allowing Objective-C to create accessors that are nonatomic:

@property (nonatomic, retain) NSString *make;

Marking your properties nonatomic does speed up access, but you might run into problems should two competing threads attempt to modify the same property at once. Atomic properties, with their lock/unlock behavior, ensure that an object update completes from start to finish before that property is released to another read or change.

  • + Share This
  • 🔖 Save To Your Account